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
Release: 2024-11-29 06:18:11
Original
277 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template