Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the code I have where I tried to execute each case with more than one value and it didn’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 know this works fine in Objective C. Can anyone tell me how I can do it in Java or I’ve to use if-else statements?

1 Answer

0 votes
by (19.7k points)

Check out the below code snippet: 

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

}

Interested in Java? Check out this Java Certification by Intellipaat. 

Browse Categories

...