This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Problem reading char from keyboard Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem reading char from keyboard" Watch "Problem reading char from keyboard" New topic
Author

Problem reading char from keyboard

Alex Gli
Greenhorn

Joined: Sep 27, 2002
Posts: 4
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

Joined: Sep 27, 2002
Posts: 4
Thanx Michael, but can you suggest a way to fix it ?
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Alex,
Try this:

Michael Morris
[ September 27, 2002: Message edited by: Michael Morris ]

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Dave Landers
Ranch Hand

Joined: Jul 24, 2002
Posts: 401
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().
 
 
subject: Problem reading char from keyboard
 
Similar Threads
BufferedReader input fails
read input from console question
Java - Works, but doesnt work...
setrequestheader() - User-Agent - no good?
determine least number of keypress