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;
}
}
}
I think whether the code will have \r
(carriage return), \n
(new line) or both \r\n
depends upon the platform.
I ran your code on a windows machine and it did print hello
twice.
You may want to check the machine you are using and the line separator defined for that environment. Please refer What are the differences between char literals '\n' and '\r' in Java? for further details.
Help on:
1. if
2. switch
3. for
4. while
5. do-while
6. break
7. continue
Choose one (q to quit): 1
choice1
hello
hello
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