繁体   English   中英

从System.in.read()读取的问题

[英]Problems reading from System.in.read()

我刚刚了解到当按下Enter以响应System.in.read() ,以下字符被放入控制台缓冲区\\r\\n 因此,当我将以下1输入到终端并按Enter键时,计算机将该语句读取为1\\r\\n 那么System.out.println("hello")应该被两次执行吗? 因为choice将存储值1 然后,将打印"hello" 然后, ignore将保持值\\r 然后,控件将while(ignore != '\\n')循环时给出。 然后, ignore将保持值\\n 然后,将打印"hello" 现在ignore = \\n ,代码将突破循环?

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;
    }
  }
}

我认为代码是否具有\\r (回车), \\n (新行)或两者\\r\\n取决于平台。

我在Windows机器上运行你的代码,它确实打印了两次hello

您可能需要检查正在使用的计算机以及为该环境定义的行分隔符。 请参考Java中字符'n'和'\\ r'之间有什么区别? 了解更多详情。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM