Switch Statement with Value Ranges in Java
In Java, it's not possible to specify a range of values in a single case of a switch statement. The code example provided below 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; }
Unlike Objective C, which supports ranges in switch statements, Java does not have such functionality. As an alternative, consider using if-else if statements:
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"); }
Here, isBetween() is a helper method that checks if a number falls within a specified range:
public static boolean isBetween(int x, int lower, int upper) { return lower <= x && x <= upper; }
By using if-else if statements, you can evaluate multiple ranges and execute the appropriate block of code.
The above is the detailed content of How Can I Handle Value Ranges in Java\'s Switch Statement?. For more information, please follow other related articles on the PHP Chinese website!