要初始化的变量出错,但是已经初始化了吗?

时间:2020-02-14 00:31:13

标签: java initialization

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

这是Java入门课程的额外学分程序;这是一种算法,可以根据用户输入的数量和价格来计算打折商品的最终价格。

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

2 个答案:

答案 0 :(得分:4)

问题在于,您只能在disRate语句中初始化IF,并且如果所有布尔条件均为假,disRate将永远不会初始化,并且disCost = totalCost * disRate;上的数学运算可能不做。

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

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

答案 1 :(得分:0)

您刚刚声明了它,还没有初始化。 您没有别的,只有if-elseif,当然,当值大于或等于100时,它将在最后一个if-else输入,但是编译器不能这么聪明。

    } else if(quantity >= 50 && quantity <=99){
        disRate = .3;

    }else  {
        disRate = .35;
    }