[英]Error for variable to be initialized but it already is?
我的 Java 代码有问题。 它还没有完成,但我有一个错误告诉我变量 disRate 尚未初始化但它已经在 else if 语句中。
这是介绍 Java 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 条件为假, disRate
将永远不会被初始化,并且disCost = totalCost * disRate;
不可能完成。
IDE 检测到这种情况并要求您用一个值初始化disRate
。
只要做double disRate = 0;
在代码的开头或添加else
语句来初始化disRate
。
你只是声明它,没有初始化。 你没有else,只有if-elseif,当然当值大于或等于100时会进入最后的if-else,但是编译器不可能这么聪明。
} else if(quantity >= 50 && quantity <=99){
disRate = .3;
}else {
disRate = .35;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.