Too many 'if' statements?

前端 未结 26 1186
天涯浪人
天涯浪人 2020-11-30 16:24

The following code does work how I need it to, but it\'s ugly, excessive or a number of other things. I\'ve looked at formulas and attempted to write a few solutions, but I

26条回答
  •  旧时难觅i
    2020-11-30 16:43

    To be quite honest, everyone has their own style of code. I wouldn't have thought performance would be affected too much. If you understand this better than using a switch case version, then carry on using this.

    You could nest the ifs , so potentially there would be a slight performance increase for your last if checks as it wouldn't have gone through as many if statements. But in your context of a basic java course it probably won't benefit.

    else if(one == 3 && two == 3) { result = 3; }
    

    So, instead of...

    if(one == 0 && two == 0) { result = 0; }
    else if(one == 0 && two == 1) { result = 0; }
    else if(one == 0 && two == 2) { result = 1; }
    else if(one == 0 && two == 3) { result = 2; }
    

    You'd do...

    if(one == 0) 
    { 
        if(two == 0) { result = 0; }
        else if(two == 1) { result = 0; }
        else if(two == 2) { result = 1; }
        else if(two == 3) { result = 2; }
    }
    

    And just reformat it as you'd prefer.

    This doesn't make the code look better, but potentially speeds it up a little I believe.

提交回复
热议问题