我无法弄清楚为什么它总是返回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;
}
我在逻辑中的某个地方搞砸了,但我没能看到哪里。 任何帮助将不胜感激。
答案 0 :(得分:9)
您缺少break
语句:
case 0:
answer = (arg1 * milligram) / milligram;
break;
...
答案 1 :(得分: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;
答案 2 :(得分:0)
嵌套的case语句非常难以阅读,而且难以调试。最好将所需的功能封装到方法调用中。
话虽如此,交换机中的任何地方都没有break
语句。无论如何,它都将落到最后一个案例(设置答案等于案件的底部)。
答案 3 :(得分:0)
您应该在switch语句中使用break
,否则您的结果可能会被取消
答案 4 :(得分:0)
除了使用break
之外,使用return
语句可以解决这个问题,同时还可以防止案件崩溃。
case 2: switch(arg3) { // if ounce
case 0: return (arg1 * milligram) / milligram;