Reading problems from System.in.read ()

I just found out that when you press enter in response to System.in.read()the console buffer is put the following symbols \r\n. Therefore, when I enter the following 1into the terminal and press enter, the computer reads this statement as 1\r\n. So shouldn't it be called System.out.println("hello")twice? Because it choiceretains value 1. And then, it "hello"will be printed. Then it ignorewill hold the value \r. The control will then be given a loop while(ignore != '\n'). Then it ignorewill hold the value \n. And then, it "hello"will be printed. And now, when ignore = \n, will the code 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;
    }
  }
}
+4
source share
1 answer

, \r ( ), \n ( ) \r\n .

Windows, hello.

, , . , char '\n' '\ r' Java? .

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
+1

Source: https://habr.com/ru/post/1599781/


All Articles