I just learned that when pressing enter in response to a System.in.read()
, the following characters are put into the console buffer, \r\n
. So when I input the following 1
into the terminal and press enter, the computer reads that statement as 1\r\n
. So shouldn't System.out.println("hello")
be excuted twice? Because choice
will store the value 1
. And then, "hello"
will be printed. Then, ignore
will hold the value \r
. Then, the control will be given while(ignore != '\n')
loop. Then, ignore
will hold the value \n
. And then, "hello"
will be printed. And now that ignore = \n
, the code will break out of the loop?
class HelpClassDemo {
public static void main(String args[])
throws java.io.IOException {
char choice, ignore;
for(;;) {
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
System.out.println(" 5. do-while");
System.out.println(" 6. break");
System.out.println(" 7. continue\n");
System.out.print("Choose one (q to quit): ");
choice = (char) System.in.read();
do {
ignore = (char) System.in.read();
System.out.println("hello");
} while(ignore != '\n');
} while(choice < '1' | choice > '7' & choice != 'q');
if(choice == 'q') break;
}
}
}