• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple console reading misunderstanding

 
Vadim Vararu
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Vadim Vararu
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does the String returned by readLine() include "/r/n" at the end?
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BufferedReader.readLine()
 
Kate Terlecka
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic