In Java,Using switch statement with a range of val

2019-01-01 04:16发布

In Java is it possible to write a switch statement where each case contains more than one value? For example (though clearly the following code won't work):

switch (num) {
    case 1 .. 5:
        System.out.println("testing case 1 to 5");
        break;
    case 6 .. 10:
        System.out.println("testing case 6 to 10");
        break;
}

I think this can be done in Objective C, are there a similar thing in Java? Or should I just use if, else if statements instead?

14条回答
泛滥B
2楼-- · 2019-01-01 04:45

other alternative is using math operation by dividing it, for example:

switch ((int) num/10) {
    case 1:
        System.out.println("10-19");
        break;
    case 2:
        System.out.println("20-29");
        break;
    case 3:
        System.out.println("30-39");
        break;
    case 4:
        System.out.println("40-49");
        break;
    default:
        break;
}

But, as you can see this can only be used when the range is fixed in each case.

查看更多
倾城一夜雪
3楼-- · 2019-01-01 04:46

Try this if you must use switch.

public static int range(int num){ 
    if ( 10 < num && num < 20)
        return 1;
    if ( 20 <= num && num < 30)
        return 2;
    return 3;
}

public static final int TEN_TWENTY = 1;
public static final int TWENTY_THIRTY = 2;

public static void main(String[]args){
    int a = 110;
    switch (range(a)){
        case TEN_TWENTY: 
            System.out.println("10-20"); 
            break;
        case TWENTY_THIRTY: 
            System.out.println("20-30"); 
            break;
        default: break;
    }
}
查看更多
登录 后发表回答