在 Java 中使用 switch 的问题

2022-01-19 00:00:00 logic switch-statement java

我不明白为什么它总是返回 arg1 的值.我正在构建一个重量转换器.

I can't figure out why it's always returning the value of arg1. I'm building a weight converter.

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;
}

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

I messed up somewhere in my logic, but I'm failing to see where. Any help would be appreciated.

推荐答案

你缺少 break 语句:

case 0: 
   answer = (arg1 * milligram) / milligram;
   break;
   ...

相关文章