Jason Goss Jason Goss - 1 year ago 77
Java Question

Java do-while with multiple string validation

Trying to create a simple program that has three options for text input. If the user types one of the three, the program moves on. If the user types something else, the program loops back and asks for the input again until a proper response is given.
Using a drop down list or other method will not work, as this is for an assignment.

System.out.print("Enter one of the following: cheese, water, or burger: ");
userMedium = user_input.nextLine( ); // store user input as a string
mediumConvert = userMedium.toLowerCase();

boolean verifyName;
if (mediumConvert.equals("cheese") || mediumConvert.equals("water") || mediumConvert.equals("burger")){
verifyName = false;
} else {
verifyName = true;

while (verifyName = true){
System.out.println("Please input a valid medium (cheese, water, or burger): ");
userMedium = user_input.nextLine( );
mediumConvert = userMedium.toLowerCase();

This is what I have set up so far, but this just keeps repeating the loop OVER AND OVER. After this section I want to execute a
to work off each of the three correct responses.

I've spent the last hour on google and YouTube, but everything I found is using integers. It seems pretty easy to validate user input when it is just a number and an operand. But how do I use three possible strings?!

Answer Source
while (verifyName = true)

You're assigning and not comparing. The expression of the assignment returns the assigned value, so your loop is equivalent to:

while (true)

You should change it to:

while (verifyName)

Basically, you should write while (verifyName == true), but it's redundant since it's like asking "Is it true that verifyName has the value true?". Also it prevents potential bugs, like just inserting one = instead of two..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download