I need to read input from console and output it in different order using InputStream

FilipKovac :

I tried to do it this way, and it is not working:

  try (Reader reader = new BufferedReader(new InputStreamReader(System.in))) {
                Stack<Character> stack = new Stack<>();
                int i = reader.read();
                while(i != -1) {
                    System.out.println("i = " + i + " = " + (char) i);
                    stack.push((char) i);
                    i = reader.read();

                }
                while(!stack.empty()) {
                    System.out.print(stack.pop());
                }
            }

Once it gets into the while(i != -1) loop, it gets into infinite loop. I found out, that once the program reaches the end of text, the final i = 10. But in Java documentation, I found, that once Reader.read() reaches end of file, it should return -1. That means I can end the loop with while(i != 10), but I want to know why it's returning 10, and not -1. Thanks for the answer

Jason :

This can be fixed by checking if i is not equal to 10 (end of line is ASCII). When we provide input like "abc" and hit enter we're actually providing asc\n. If we check if \n (10) has been provided we can break out of the loop.

while (i != -1 && i != 10) {

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=349090&siteId=1