Issue with using switch in Java

江枫思渺然 提交于 2019-12-02 06:32:41

You are missing break statements:

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

rewrite every case like this

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;

Nested case statements are pretty hard to read, and tough to debug. It'd be a better idea to encapsulate the functionality you need into a method call instead.

That being said, there's no break statement anywhere in your switch. Regardless of the case, it will fall through to the last case (setting answer equal to the bottom of the case).

You should be using break in switch statements,else your result may get detoriated

Other than using break, using return statements does the trick as well as it also prevents falling through cases.

case 2: switch(arg3) { // if ounce
    case 0: return (arg1 * milligram) / milligram;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!