Intellipaat 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?

2 Answers

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. 

0 votes
by (1.9k points)

switch case statements can be used to execute a specific for a certain parameter or condition. The usage os switch case statement is demonstrated in the below code:

It is not possible in Java to provide a range in each case. But it can be achieved by using a set of if-else statements:

public class AgeCategory {

public static void main(String[] args) {

int age_1 = 25;

String category = getCategory(age_1);

 

switch (category) {

case "Child":

System.out.println("You are a child.");

break;

case "Teen":

System.out.println("You are a teenager.");

break;

case "Adult":

System.out.println("You are an adult.");

break;

default:

System.out.println("Invalid Age");

break;

}

}


 

public static String getCategory(int age_2) {

if (age_2 >= 0 && age_2 <= 12) {

return "Child";

} else if (age_2 >= 13 && age_2 <= 19) {

return "Teen";

} else if (age_2 >= 20 && age_2 <= 64) {

return "Adult";

} else if (age_2 >= 65) {

return "Senior";

} else {

return "Invalid";

}

}

}


 

Related questions

0 votes
2 answers

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...