0

I wrote a program which prints out the characters of the sentence (or word) wrote by the user to the console. I thought that the program will end after I gave the first input. But it didn't and kept taking inputs and printing it even after it printed the first sentence. Can you explain me why it happened so? I am new to this. Here is the program:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

/*
 * This program prints out the characters written in the console
 * line by line.
 */
public class ReaderProgram {
    public static void main(String args[]) throws IOException{

        char c;

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        do{
            //reads character and stores it in c
            c = (char) br.read();
            //prints out c
            System.out.println(c);
        }while(c != -1);
        //'while' checks if c is -1 (-1 means end of the stream)
    }
}

Output is shown here (Input to console is show like this):

Epic
E
p
i
c




Dream
D
r
e
a
m

dark32
  • 259
  • 3
  • 14
  • Explain us why you think it should stop. Use the javadoc of Reader.read() to help you. Also think about the following points: what is the end of the System.in stream? What is the range of values of a char? – JB Nizet Nov 25 '14 at 15:14
  • 1
    The `System.in` stream does not normally end, see http://stackoverflow.com/questions/3197025/end-of-fileeof-of-standard-input-stream-stdin . – JimmyB Nov 25 '14 at 15:30
  • @HannoBinder excellent point, br.read() will be blocking for that reason. I missed that. The code had two problems with it. Add that as an answer. – Chris K Nov 25 '14 at 16:03

1 Answers1

2

You have cast the result of br.read() too early.

br.read() returns a int, which has a larger storage capacity than a char. char is neither signed nor large enough to store both -1 and the full UTF-16 range of values.

By casting the result to a char before comparing it to -1 you have effectively converted -1 to Character.MAX_VALUE. Which can never equal -1.

Consider the following code:

public static void main( String[] args ) {
    char v = (char) -1;
    System.out.println( "v = " + (int) v );
}

It will print 65535, and not -1.

Chris K
  • 11,622
  • 1
  • 36
  • 49