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条回答
唯独是你
2楼-- · 2019-01-01 04:21

@missingfaktor 's answer is indeed correct but a bit over-complicated. Code is more verbose (at least for continuous intervals) then it could be, and requires overloads/casts and/or parameterization for long, float, Integer etc

if (num < 1)
    System.Out.Println("invalid case: " + num); // you should verify that anyway
else if (num <= 5)
    System.Out.Println("1 to 5");
else if (num <= 10)
    System.Out.Println("6 to 10");
else if (num <= 42)
    System.Out.Println("11 to 42");
else    
    System.Out.Println("43 to +infinity");
查看更多
闭嘴吧你
3楼-- · 2019-01-01 04:23

Here is a beautiful and minimalist way to go

(num > 1 && num < 5) ? first_case_method() 
                     : System.out.println("testing case 1 to 5")
                     : (num > 5 && num < 7)  ? System.out.println("testing case 1 to 5") 
                     : (num > 7 && num < 8)  ? System.out.println("testing case 1 to 5") 
                     : (num > 8 && num < 9)  ? System.out.println("testing case 1 to 5") 
                     : ... 
                     : System.out.println("default");
查看更多
栀子花@的思念
4楼-- · 2019-01-01 04:24
  case 1: case 2: case 3: case 4: case 5: 
         System.out.println("testing case 1 to 5");
         break;
  case 6: case 7: case 8: case 9: case 10:
         System.out.println("testing case 6 to 10");
         break;
  default:
         System.out.println("default"); 
查看更多
旧时光的记忆
5楼-- · 2019-01-01 04:25

It's possible to group several conditions in the same case statement using the mechanism of fall through allowed by switch statements, it's mentioned in the Java tutorial and fully specified in section §14.11. The switch Statement of the Java Language Specification.

The following snippet of code was taken from an example in the tutorial, it calculates the number of days in each month (numbered from month 1 to month 12):

switch (month) {
    case 1: case 3: case 5:
    case 7: case 8: case 10:
    case 12:
        numDays = 31;
        break;
    case 4: case 6:
    case 9: case 11:
        numDays = 30;
        break;
    case 2:
        if (((year % 4 == 0) && 
             !(year % 100 == 0))
             || (year % 400 == 0))
            numDays = 29;
        else
            numDays = 28;
        break;
    default:
        System.out.println("Invalid month.");
        break;
}

As you can see, for covering a range of values in a single case statement the only alternative is to list each of the possible values individually, one after the other. As an additional example, here's how to implement the pseudocode in the question:

switch(num) {
    case 1: case 2: case 3: case 4: case 5:
        System.out.println("testing case 1 to 5");
        break;
    case 6: case 7: case 8: case 9: case 10:
        System.out.println("testing case 6 to 10");
        break;
}
查看更多
旧人旧事旧时光
6楼-- · 2019-01-01 04:25

Use a NavigableMap implementation, like TreeMap.

/* Setup */
NavigableMap<Integer, Optional<String>> messages = new TreeMap<>();
messages.put(Integer.MIN_VALUE, Optional.empty());
messages.put(1, Optional.of("testing case 1 to 5"));
messages.put(6, Optional.of("testing case 6 to 10"));
messages.put(11, Optional.empty());

/* Use */
messages.floorEntry(3).getValue().ifPresent(System.out::println);
查看更多
皆成旧梦
7楼-- · 2019-01-01 04:26

The closest you can get to that kind of behavior with switch statements is

switch (num) {
case 1:
case 2:
case 3:
case 4:
case 5:
     System.out.println("1 through 5");
     break;
case 6:
case 7:
case 8:
case 9:
case 10:
     System.out.println("6 through 10");
     break;
}

Use if statements.

查看更多
登录 后发表回答