Get rid of ugly if statements

后端 未结 25 2102
借酒劲吻你
借酒劲吻你 2020-12-02 05:59

I have this ugly code:

if ( v > 10 ) size = 6;
if ( v > 22 ) size = 5;
if ( v > 51 ) size = 4;
if ( v > 68 ) size = 3;
if ( v > 117 ) size = 2         


        
25条回答
  •  渐次进展
    2020-12-02 06:26

    It is interesting that there are plenty of beautiful answers for a simple "ugly" question. I like mfloryan's answer best, however I would push it further by removing the hard-coded array inside the method. Something like,

    int getIndex(int v, int[] descArray) {
        for(int i = 0; i < descArray.length; i++)
            if(v > descArray[i]) return i + 1;
        return 0;
    }
    

    It now becomes more flexible and can process any given array in descending order and the method will find the index where the value 'v' belongs.

    PS. I cannot comment yet on the answers.

提交回复
热议问题