Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem reading char from keyboard

 
Alex Gli
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Alex Gli
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx Michael, but can you suggest a way to fix it ?
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Alex,
Try this:

Michael Morris
[ September 27, 2002: Message edited by: Michael Morris ]
 
Dave Landers
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic