Jordan.McBride
Jordan.McBride

Reputation: 267

How to Exit a While loop containing a switch - Java

This is for an assignment for a computers class. This is going beyond what the teacher asked for, so I am not asking you people to do my school work for me. What I am not able to understand is how to exit the switch and the while. I know that using break; will exit the while loop, and using break; will exit a switch. What I am looking for is some code that will exit a switch and a while loop at the same time. What I could do is just use

if (upgrade == 1){
    // Do Stuff
}

if (upgrade == 2){
    // Do Stuff
}

if (upgrade == 3){
    // Do Stuff
}

if (upgrade == 4){
    // Do Stuff
}

if (upgrade == 0){
    break;    // Exit the while loop
}

However, the teacher does not want us to use that format, but instead use switches. I also thought that I could just add the

if (upgrade == 0){
    Break;
}

To the bottom, but that still is not using a switch, and my teacher would not be happy with it. Is there any way to exit a swtich and a while loop at the same time?

This is what he wants the code to look like:

while (timesLeveled > 0){

    System.out.println("Upgrade Stats");

    upgrade = chooseUpgrade();    // retrieves the number for upgrade

    switch (upgrade){
    case 1: 
        // Do stuff if upgrade is 1
        break;


    case 2:
                    // Do stuff if upgrade is 2
        break;


    case 3: 
        // Do stuff if upgrade is 3
        break;

    case 4:
        // Do stuff if upgrade is 4
        break;


    case 0:

        break;

    }   // Closes off Switch

            timesLeveled--; // resets level counter

        }   // Closes off while (timesLeveled)

Upvotes: 1

Views: 3795

Answers (1)

I would usually recommend against using a switch at all when you have the option, but if you have to stick with it, you probably want the break with label.

WhileLoop: while (timesLeveled > 0) {
    ...
    case n:
        // do stuff
        break WhileLoop;
    ...
}

Note that this usage usually means that your code needs more than one significant cleanup (Replace Conditional with Polymorphism, loop improvement, etc.).

Upvotes: 6

Related Questions