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
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) {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.