-1

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?

martijnn2008
  • 3,552
  • 5
  • 30
  • 40
Nighthawk
  • 5
  • 3

3 Answers3

1

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:
// ....
}
Robin Krahl
  • 5,268
  • 19
  • 32
0
switch (waistMeasure) {
    case 26:
    case 27:
        System.out.println("You are a Small.");
        break PANTS;
    case 28:
    case 29:
        System.out.println("You are a Medium.");
        break PANTS;
    case 30:
    case 31:
    case 32:
    case 33:
    case 34:
        System.out.println("You are a Large.");
        break PANTS;
    default
        System.out.println("Invalid input");
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
-1

Do you mean something like this?

Notice that you have to use the PANTS label for the break statement to exit the loop, otherwise they just break from the switch and will continue looping.

PANTS: for (;;) {
    int waistMeasure = in.nextInt();
    switch (waistMeasure) {
        case 26:
        case 27:
            System.out.println("You are a Small.");
            break PANTS;
        case 28:
        case 29:
            System.out.println("You are a Medium.");
            break PANTS;
        case 30:
        case 31:
        case 32:
        case 33:
        case 34:
            System.out.println("You are a Large.");
            break PANTS;
        default:
            System.out.println("Invalid input");
    }
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Why the downvote? Someone don't like break on label? I find it more clear than using boolean flag to control loop, especially if loop is large (cannot be seen in full on screen without scrolling). – Andreas Jun 06 '16 at 18:56