如何将在此 switch 语句中找到的值返回给类的其余部分以供使用(我想在该 switch 语句之外使用 oneTotal、twoTotal 等)?下面是 switch 语句的代码:
switch(itemNo){
case 1:
double oneTotal = 2.98 * userQuantity;
return oneTotal;
case 2:
double twoTotal = 4.50 * userQuantity;
return twoTotal;
case 3:
double threeTotal = 9.98 * userQuantity;
return threeTotal;
case 4:
double fourTotal = 4.49 * userQuantity;
return fourTotal;
case 5:
double fiveTotal = 6.87 * userQuantity;
return fiveTotal;
}
在 switch 语句的外面,我希望一旦用户停止使用 switch 语句(我在 while 循环中使用它)就将 FiveTotal 添加起来,然后希望返回五个总计以在主程序中使用类的方法(switch 语句位于其自己的 double 、非 void 类中,因此它可以返回值)。
最佳答案
在 Java 14 上,您可以使用
double total = switch(itemNo){
case 1 -> 2.98 * userQuantity;
case 2 -> 4.50 * userQuantity;
case 3 -> 9.98 * userQuantity;
case 4 -> 4.49 * userQuantity;
case 5 -> 6.87 * userQuantity;
};
关于java - 如何返回在 switch 语句中找到的值 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28547587/