I have written a simple progy to test keyboard input. But something is wrong. I added while to my progy and want it to get input from user until user inputs character 'y' or 'n'. The problem is when I ran the progy and input let's say 'a', program automaticaly loops 3 times through while and after that asks for another input. What am I doing wrong? Source:
[ September 27, 2002: Message edited by: Alex Gli ]
Joined: Sep 27, 2002
Thanx Michael, but can you suggest a way to fix it ?
Your while condition will always be true: while ( c != 'y' || c != 'n' ) ... For example let c be 'y': y != y => false y != n => true false || true => true ...and the loop keeps rolling.
You really wanted while ( c != 'y' && c != 'n' ) ...
Also, the thing looped 3 times because the read() method just reads a single char. You probably typed a character (a or y or something) and then pressed ENTER (which is actually two chars on Windows: CR + LF). Since the while loop is always true, it read() all three of those chars. If you want to just look at characters typed, then read() is correct. But if you are trying to look at typed lines (wait till they press ENTER), you probably want to look at something like BufferedReader.readLine().