GeeCON Prague 2014*
The moose likes I/O and Streams and the fly likes Simple console reading misunderstanding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Simple console reading misunderstanding" Watch "Simple console reading misunderstanding" New topic
Author

Simple console reading misunderstanding

Vadim Vararu
Ranch Hand

Joined: Jan 03, 2009
Posts: 147
When i run this, console is waiting for me to insert some data. If i insert more chars, it ok. I get first two chars on the screen (cause of System.out). But, when i insert only one character, why program just write that one and that's all. Doesn't it have to prompt for the second character? As i understand i insert for instance "d" and push Enter. After that program sees that input stream is empty and i should insert anything more, but it doesn't happen.



If you think you've done too much, usually it means you've done too few.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Add this line: If you enter only one character (let's say "d"), you'll see that it prints 100, 13. That 13 is the carriage return (\r) that follows just before the line break (\n) on Windows systems. If you add another br.read() you'll get 10 (\n).

The thing is, read() returns all characters, including end-of-line characters like \r and \n. Perhaps readLine() will be more to your liking - that will strip off \r and \n. You then get a full string which you can investigate using the length() and charAt(int) methods.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Vadim Vararu
Ranch Hand

Joined: Jan 03, 2009
Posts: 147
Does the String returned by readLine() include "/r/n" at the end?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

BufferedReader.readLine()
Kate Terlecka
Greenhorn

Joined: May 13, 2009
Posts: 12
Vadim Vararu wrote:Does the String returned by readLine() include "/r/n" at the end?


no, its safe to use it when you have to read multiple variables and you don't have to trim it


--
Never argue with an idiot.
He will bring you down to his level
and beat you with experience.
 
GeeCON Prague 2014
 
subject: Simple console reading misunderstanding