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 seems I'm getting into an infinite loop and when I press "Enter" the program does not come to an end. My code is below:
InputStreamReader instream = new InputStreamReader(System.in); BufferedReader buffer = new BufferedReader(instream); line= buffer.readLine(); while (line!=null){ length = length + line.length(); line= buffer.readLine(); }
Could you please tell me what I'm doing wrong?
Another way to read multiple lines from the console can be done using the synchronized BufferedReader class in Java. The idea is to read each line using the readLine() method and use String. split() to split the line into individual tokens using whitespace as a delimiter. We can also use the StringTokenizer class.
The readLine() method of Console class in Java is used to read a single line of text from the console. Syntax: public String readLine() Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console.
BufferedReader The readLine() method reads a line of text from the file and returns a string containing the contents of the line, excluding any line-termination characters or null.
One line of code using Java 8:
line = buffer.lines().collect(Collectors.joining());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With