Java switch statement multiple cases

前端 未结 13 1153
后悔当初
后悔当初 2020-11-27 14:43

Just trying to figure out how to use many multiple cases for a Java switch statement. Here\'s an example of what I\'m trying to do:

switch (variable)
{
    c         


        
13条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 14:54

    According to this question, it's totally possible.

    Just put all cases that contain the same logic together, and don't put break behind them.

    switch (var) {
        case (value1):
        case (value2):
        case (value3):
            //the same logic that applies to value1, value2 and value3
            break;
        case (value4):
            //another logic
            break;
    }
    

    It's because case without break will jump to another case until break or return.

    EDIT:

    Replying the comment, if we really have 95 values with the same logic, but a way smaller number of cases with different logic, we can do:

    switch (var) {
         case (96):
         case (97):
         case (98):
         case (99):
         case (100):
             //your logic, opposite to what you put in default.
             break;
         default: 
             //your logic for 1 to 95. we enter default if nothing above is met. 
             break;
    }
    

    If you need finer control, if-else is the choice.

提交回复
热议问题