Home >Java >javaTutorial >How Can I Handle Ranges of Values in Java\'s Switch Statement?

How Can I Handle Ranges of Values in Java\'s Switch Statement?

DDD
DDDOriginal
2024-11-29 06:18:11327browse

How Can I Handle Ranges of Values in Java's Switch Statement?

Switch Statement with Range of Values in Cases in Java

Java's switch statement allows you to match a variable against a set of constant values to execute specific code for each condition. However, it's not possible to specify a range of values for a single case, as illustrated in the example provided:

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;
}

Alternative Solution:

Since Java does not natively support ranges in switch cases, an alternative solution is to use a combination of if-else if statements. This approach involves creating a function to check if a given value falls within a specified range:

public static boolean isBetween(int x, int lower, int upper) {
  return lower <= x && x <= upper;
}

Using this function, you can construct a series of if-else if statements to determine which range the num variable belongs to and execute the corresponding code:

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");
}

The above is the detailed content of How Can I Handle Ranges of Values in Java\'s Switch Statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn