tonyisapony
tonyisapony

Reputation: 89

Switch Statement and While Loop

I am writing a database program that allows the user to search for employees and it opens up a menu for them.in my Main() I have to prompt the User to press m to open up the menu() or q to open up finalStats() any other input is invalid. My problem is that i can't get a while loop to work properly. whenever i hit m it works and when i hit q it works fine, but whenever i hit a key other than those there's an infinite loop and it just infinitely prints out "Please enter a valid character"

boolean end = false;
    System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
    String entered = scan.next();
    while (end == false)
    switch(entered)
    {
    case "m":
    case "M":
        menu();
    case "q":
    case "Q":
        finalStats();
        end = true;
    default:
        System.err.println("Please enter a valid character");
    }

Upvotes: 2

Views: 5735

Answers (3)

ford prefect
ford prefect

Reputation: 7388

I think this fixes your problems:

boolean end = false;
System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
String entered = scan.next();
while (end == false)
{
switch(entered)
    {
    case "m":
    case "M":
        menu();
        break;
    case "q":
    case "Q":
        finalStats();
        end = true;
        break;
    default:
        System.err.println("Please enter a valid character");
        break;
    }
    System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final                     stats");
    String entered = scan.next();
}

You have a couple of problems. You are missing break; in your cases and you are not soliciting new input inside of the while loop. I am not sure exactly what you are doing whether you want to solicit an option more than once.

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

You are missing the break statement in your switch case. Also move your while statement to allow user to scan.

Try this:

boolean end = false;
while (end == false)
    System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
    String entered = scan.next();

    switch(entered)
    {
    case "m":
    case "M":
        menu(); 
        break;
    case "q":
    case "Q":
        finalStats();
        end = true;
        break;
    default:
        System.err.println("Please enter a valid character");
    }

Upvotes: 0

Keppil
Keppil

Reputation: 46219

You need to move the line

while (end == false)

to before the scan.next(), to allow the user to try again. Make sure to add braces when you do this, so the while affects the entire program snippet you are showing. It is considered a good practice to always use curly braces for loops and if statements.

Also, as @RahulTripathi points out, you need to add break statements at the end of your case blocks.

Upvotes: 2

Related Questions