我的Java代码遇到了问题。它还没有完成,但是我有一个错误,告诉我变量disRate还没有初始化,但是它已经在else if语句中了。
这是一个针对Intro to 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发布于 2020-02-14 08:38:48
问题是您只能在IF语句中初始化disRate,如果所有布尔条件都为假,disRate将永远不会初始化,disCost = totalCost * disRate;上的数学运算也无法完成。
集成开发环境检测到这种情况,并要求您使用一个值初始化disRate。
只需在代码开头执行double disRate = 0;或添加else语句来初始化disRate即可。
发布于 2020-02-14 08:37:59
您只是声明了它,而没有初始化它。你没有else,只有if-else if,当然,当值大于或等于100时,会进入最后一个if-else,但是编译器不可能更智能。
} else if(quantity >= 50 && quantity <=99){
disRate = .3;
}else {
disRate = .35;
}https://stackoverflow.com/questions/60218423
复制相似问题