Knight506 Knight506 - 17 days ago 5
Java Question

testing char in a java while loop

I'm trying to make a while loop in java, and it's supposed to run until the char variable answer is either a or d. If the user does not answer properly, the program has them answer again. It looks like this:

while(answer != 'a' || answer != 'd')
{
System.out.println("Please make sure you typed and correctly formatted your answer");
answer = keyboard.next().charAt(0);
}


When I enter a or d, the while loop doesn't end. It just repeats. Is there a simple fix to this?

Answer
while(answer != 'a' || answer != 'd')

becomes

while(answer != 'a' && answer != 'd')

If its equal to a, then its not equal to d which satisfies the condition of the loop.

Comments