小编典典

在Java中使用switch的问题

java

我不知道为什么它总是返回arg1的值。我正在建立一个体重转换器。

public double convert(double arg1,int arg2,int arg3) {
    // arg1 = amount, arg2 = from, arg3 = to
    double milligram = 1;
    double gram = 1000;
    double ounce = 28349.5;
    double pound = 453592;
    double answer = 0;
    switch(arg2) {
    case 0: switch(arg3) { // if milligram
            case 0: answer = (arg1 * milligram) / milligram;
            case 1: answer = (arg1 * milligram) / gram;
            case 2: answer = (arg1 * milligram) / ounce;
            case 3: answer = (arg1 * milligram) / pound;
    }
    case 1: switch(arg3) { // if gram
            case 0: answer = (arg1 * gram) / milligram;
            case 1: answer = (arg1 * gram) / gram;
            case 2: answer = (arg1 * gram) / ounce;
            case 3: answer = (arg1 * gram) / pound;
    }
    case 2: switch(arg3) { // if ounce
            case 0: answer = (arg1 * ounce) / milligram;
            case 1: answer = (arg1 * ounce) / gram;
            case 2: answer = (arg1 * ounce) / ounce;
            case 3: answer = (arg1 * ounce) / pound;
    }
    case 3: switch(arg3) { // if pound
            case 0: answer = (arg1 * pound) / milligram;
            case 1: answer = (arg1 * pound) / gram;
            case 2: answer = (arg1 * pound) / ounce;
            case 3: answer = (arg1 * pound) / pound;
    }
    } // end arg2 switch
    return answer;
}

我弄乱了逻辑,但看不到哪里。任何帮助,将不胜感激。


阅读 293

收藏
2020-11-26

共1个答案

小编典典

您缺少break声明:

case 0: 
   answer = (arg1 * milligram) / milligram;
   break;
   ...
2020-11-26