Skip to content

Do-while loop doesn’t work for validating using a .equals method (Java) [closed]

For an assignment, I had to make a program to see if the user input contained any of the three letters: r, c or p. If it was wrong, I had to keep asking the user to retype the input until the user typed the correct answer.[Please ignore the code in the comments]

I tried using a do while loop to do the validation and I tested it myself, but instead of the invalid error message being returned only as long as the conditions were met, it returns it no matter what the user input was. The do statement ignored even the “valid inputs” and prints an invalid message regardless.[enter image description here]



The main problem in your program is the condition you specified for the loop. If the input is not “c” or not “r” or not “p” the loop will continue. But the input will always be not “c” or not “r”, if your input is for example “p”. You should seperate the conditions with an and not an or.

while (!customerCode.contentEquals("r") && !customerCode.contentEquals("c") && !customerCode.contentEquals("p"));