Issue with using switch in Java

前端 未结 5 1742
谎友^
谎友^ 2021-01-23 16:22

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) {
    //         


        
相关标签:
5条回答
  • 2021-01-23 16:33

    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;
    
    0 讨论(0)
  • 2021-01-23 16:41

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

    0 讨论(0)
  • 2021-01-23 16:45

    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;
    
    0 讨论(0)
  • 2021-01-23 16:50

    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).

    0 讨论(0)
  • 2021-01-23 16:53

    You are missing break statements:

    case 0: 
       answer = (arg1 * milligram) / milligram;
       break;
       ...
    
    0 讨论(0)
提交回复
热议问题