-4

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]

Rohith
  • 13
  • 2
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include your source code as a working [mcve], which can be compiled and tested by others. [Please do not upload images of code/errors when asking a question.](https://meta.stackoverflow.com/q/285551) – Progman Nov 05 '22 at 19:24
  • You might want to look into something called "De Morgan's law", see https://stackoverflow.com/questions/20043664/de-morgans-law – Progman Nov 05 '22 at 19:30

2 Answers2

3

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"));
Progman
  • 16,827
  • 6
  • 33
  • 48
1

You need to use a while loop here, not a do..while. A do..while loop runs its body at least once, and then checks the condition - so it will show the error message at least once no matter what. Instead, use a while loop, which checks the condition first:

while (input does not contain r, c or p) {
  // Show error, ask for new input
}
// Input is now valid
HKTE
  • 167
  • 5
  • Oh, I tried that, but for some reason, the error message still shows up regardless of the input. Maybe I need to change something about the order of the customercode declaration and the System.out.print statement. But thank you for trying to help! – Rohith Nov 05 '22 at 19:30