• Post Reply Bookmark Topic Watch Topic
  • New Topic

flow of control for BufferedReader  RSS feed

 
Satish Kumar
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
i was trying to read the characters from console by using the following program
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class BRRead {
public static void main(String args[]) {
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter characters 'q' to exit");
try {
do{
c= (char)br.read();
System.out.println(c);
}while(c!='q');
}
catch(IOException ioex) {
System.out.println("io exception is "+ioex);
}
}
}

here are sample runs
1)
enter characters 'q' to exit
abcq
a
b
c
q
Press any key to continue . . .

works well as expected here

2)
enter characters 'q' to exit
abc
a
b
c



ef
e
f



q
q
Press any key to continue . . .

the problem here is i am unable to understand the flow of control
after entering abc it prints a b c in three lines the where there are 4 empty lines in output and then when i give ef how is the control goes to try block then again seeing the 4 blank lines..
can anyone explain me the flow of control for this program.
Thanks in advance
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you enter "abc", it is actually 4 characters (5 under Windows). The last character is the line feed (Windows uses carriage return / line feed combination). I am guessing you are using Windows here.

Anyway, with Windows, two of the lines are caused by the println itself, for the two extra characters. The other two lines should be caused by the characters (CR and LF) itself.

Henry
 
Bert Bates
author
Sheriff
Posts: 8954
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
intermediate forum bound...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!