Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using switch statement with a range of value in each case?

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?

like image 902
davidx1 Avatar asked Jun 03 '12 20:06

davidx1


People also ask

Can switch case have a range of values?

Using range in switch case in C/C++ You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.

Can case in switch statement have multiple values?

The switch can includes multiple cases where each case represents a particular value. Code under particular case will be executed when case value is equal to the return value of switch expression. If none of the cases match with switch expression value then the default case will be executed.

How many cases can you have in a switch statement?

Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.


2 Answers

Java has nothing of that sort. Why not just do the following?

public static boolean isBetween(int x, int lower, int upper) {   return lower <= x && x <= upper; }  if (isBetween(num, 1, 5)) {   System.out.println("testing case 1 to 5"); } else if (isBetween(num, 6, 10)) {   System.out.println("testing case 6 to 10"); } 
like image 178
missingfaktor Avatar answered Sep 28 '22 01:09

missingfaktor


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.

like image 40
Jeffrey Avatar answered Sep 28 '22 03:09

Jeffrey