我的 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/