java - 如何返回在 switch 语句中找到的值 Java

标签 java switch-statement return double user-input

如何将在此 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/

相关文章:

java - Midi 淡入淡出和音量控制

java - 如何更改单选按钮的高度

javascript - 开关内开关替代

使用 switch 语句将两位数字转换为单词

javascript - 您能否像将函数转换为 Javascript 中的字符串那样,将方法转换为 Java 中的字符串?

java - java中的返回问题

java - Infinispan 操作模式

java - 如何从同一 WildFly 服务器上的不同部署访问 Ear 文件的 lib 文件夹模块?

string - 在Groovy中打开字符串值会产生意外的结果

c - 双尾递归需要解释