1

我不明白为什么它总是返回 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;
}

我在逻辑的某个地方搞砸了,但我看不到在哪里。任何帮助,将不胜感激。

4

5 回答 5

9

您缺少break陈述:

case 0: 
   answer = (arg1 * milligram) / milligram;
   break;
   ...
于 2012-10-06T18:46:05.157 回答
2

像这样重写每个案例

case 2: switch(arg3) { // if ounce
        case 0: answer = (arg1 * ounce) / milligram;break;
        case 1: answer = (arg1 * ounce) / gram;break;
        case 2: answer = (arg1 * ounce) / ounce;break;
        case 3: answer = (arg1 * ounce) / pound;break;
于 2012-10-06T18:47:20.403 回答
0

嵌套的 case 语句很难阅读,也很难调试。将您需要的功能封装到方法调用中会是一个更好的主意。

话虽如此,break您的开关中没有任何声明。无论哪种情况,它都会落到最后一种情况(设置答案等于案例的底部)。

于 2012-10-06T18:46:14.083 回答
0

你应该break在 switch 语句中使用,否则你的结果可能会被破坏

于 2012-10-06T18:47:27.590 回答
0

除了 using break, usingreturn语句也可以做到这一点,它还可以防止案例失败。

case 2: switch(arg3) { // if ounce
    case 0: return (arg1 * milligram) / milligram;
于 2012-10-06T18:52:28.270 回答