Nighthawk Nighthawk - 6 months ago 9
Java Question

How to convert a comparative if statement to a switch case statement?

I'm new to java programming and I'm having trouble figuring this out.

Here's my code:

boolean running = true;
PANTS:
while (running) {
int waistMeasure = in.nextInt();

if (waistMeasure >= 26 && waistMeasure < 28){
System.out.println("You are a Small.");
break;
}
if (waistMeasure >= 28 && waistMeasure < 30){
System.out.println("You are a Medium.");
break;
}
if (waistMeasure >= 30 && waistMeasure <= 34){
System.out.println("You are a Large.");
break;
}

else {
System.out.println("Invalid input");
}
}


Is there any way to convert this into switch case statements?

Answer

Yes, there is – but you’d have to create a case for each value (as shown below). You cannot express a range of values with a single case. So if you want readable and maintainable code, you should stick with ifs.

switch (waistMeasure) {
case 26:
case 27:
    System.out.println("You are a Small.");
    running = false;
    break;
case 28:
case 29:
// ....
}