I want to type a multiple line text into the console using a BufferedReader and when I hit \"Enter\" to find the sum of the length of the whole text. The problem is that it
line
will not be null when you press enter; it will be an empty string.
Take note of what the BufferedReader JavaDoc says about readLine()
:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
And readLine()
returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So when you press [Enter], you are giving the BufferedReader
a new line containing only \n
, \r
, or \r\n
. This means that readLine()
will return an empty string.
So try something like this instead:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line = buffer.readLine();
while( (line != null) && (!line.isEmpty()) ){
length = length + line.length();
line = buffer.readLine();
}