Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems reading from System.in.read()

Tags:

java

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;
    }
  }
}
like image 932
aejhyun Avatar asked Nov 09 '22 08:11

aejhyun


1 Answers

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
like image 86
Smiles Avatar answered Nov 15 '22 06:11

Smiles