我试图理解 switch
陈述。
所以我已经解决了这个问题。
“一家软件公司销售的软件包零售价为 99 美元。数量有折扣
根据以下内容:
10-19 = 20%
20-49 = 30%
50-99 = 40%
100 or more = 50%
编写一个程序,要求用户输入购买的包裹数量。然后程序应该显示折扣金额(如果有)和总金额 折扣后购买。
我使用 if
解决了这个问题else if
结构和几个关系运算符,看起来像这样
//Determine total price based on discounts
if (x >= 10 && x <= 19)
{
total = (((x*99) - (x * 99)* .2));
JOptionPane.showMessageDialog(null, "Your total is $" + total
+ " with a 20% discount");
}
else if(x >= 20 && x <= 49)
{
total = (((x*99) - (x * 99)* .3));
JOptionPane.showMessageDialog(null, "Your total is $" + total
+ " with a 30% discount.");
.
.
.
我想知道是否可以将可能的数字范围存储在单个变量中,然后将其用于 case
声明?使用 switch
有意义吗?在这种情况下的声明?我尝试将可能的数字范围(本质上是一个表达式,存储在声明为 Boolean
的变量中)拟合到变量中,但由于我声明了变量(x),所以解析了 Integer
用户为 JOptionPane
输入的任何数字的值输入对话框不允许我使用 boolean 变量。所以我仍然有点困惑 switch
到底是怎么回事?声明有效,但我希望能够帮助您了解使用 switch
时会发生什么和不会发生什么。声明。
最佳答案
怎么样
if(total >= 100)
{
//use 50%
}
else if(total >= 50)
{
//use 40%
}
else if(total >= 20)
{
//use 30%
}
else if(total >= 10)
{
//use 20%
}
else
{
//no discount
}
如果你到达 total >= 50
的 else if ,你已经知道 total < 100
。等等。这确实是利用好if..else if..else
的原因。语句,当您可以根据前面的语句推断条件时。如果您仅使用 if 语句,您现在的代码将是等效的。
还有
total = (((x*99) - (x * 99)* .2));
最好写成
total = x * 99 * (1-.2)
关于java - switch 语句中的值范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19233234/