java - 变量已初始化但已初始化时出错?

标签 java initialization

我的 Java 代码遇到问题。它还没有完成,但我有一个错误告诉我变量 disRate 尚未初始化,但它已在 else if 语句中。

这是 Java 入门类(class)的额外学分类(class);它是一种根据用户输入的数量和价格计算折扣商品最终价格的算法。

import java.util.Scanner;


public class DiscountDemo {

    public static void main(String[] args) {
        // start code here

        //variables
        int quantity;
        double itemPrice, totalCost, disRate, disCost, netAmount;

        Scanner get = new Scanner(System.in);

        //user prompt
        System.out.print("Enter the quantity of an item: --> ");
        quantity = get.nextInt();

        System.out.print("Enter the price of an item: --> ");
        itemPrice = get.nextInt();

        //decision statements
        if(quantity <= 0 || itemPrice <=0)
        {
            System.out.println("\nInvalid Data!\n");

        }
        else if(quantity <= 9)
        {
            disRate = 0;

        }//if quantity <=9 end
        else if(quantity >= 10 && quantity <= 19)
        {
            disRate = .1;

        }//if quantity >=10 || <= 19 end
        else if(quantity >= 20 && quantity <= 49)
        {
            disRate = .2;

        }//if quantity >=20 || <= 49 end
        else if(quantity >= 50 && quantity <=99)
        {
            disRate = .3;

        }//if quantity >=50 || <= 99 end
        else if(quantity >= 100)
        {
            disRate = .35;

        }//if quantity >=100 end

        //calculation
        totalCost = quantity * itemPrice;
        disCost = totalCost * disRate;
        netAmount = itemPrice - disCost;


    } //main end

} //class end

最佳答案

问题是您仅在 IF 语句中初始化 disRate,如果所有 boolean 条件均为 false,disRate 将永远不会初始化,并且disCost =totalCost * disRate; 上的数学无法完成。

IDE 检测到这种情况并要求您使用一个值初始化 disRate

只需在代码开头执行 double disRate = 0; 或添加 else 语句即可初始化 disRate

关于java - 变量已初始化但已初始化时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218423/

相关文章:

java - 如何使用正则表达式从字符串中解析数字

java - Firebase 身份验证错误 getGoogleApiForMethod() 返回 Gms :

java - 使用 RProtoBuf( Protocol Buffer )从 R 调用 Java 函数

java - Java 中由 new String() 和 new String (""进行的字符串初始化有什么区别?

c - 如何判断多维数组是否未分配给?

Java 组合框未从 SQL 填充

Java - 如何检查 JFrame 是否关闭

c++ - 可以使用 C++ 结构聚合初始化来创建临时实例吗?

c++ - 就地成员初始化和聚合初始化

java - 初始化为 null 和不初始化为 null 的内存使用情况