Read all lines with BufferedReader

后端 未结 7 695
醉梦人生
醉梦人生 2020-12-08 14:24

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

相关标签:
7条回答
  • 2020-12-08 15:12

    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();
    }
    
    0 讨论(0)
提交回复
热议问题