【问题标题】:Problems reading from System.in.read()从 System.in.read() 读取的问题
【发布时间】:2015-10-17 02:57:34
【问题描述】:

我刚刚了解到,当按下回车以响应System.in.read() 时,会将以下字符放入控制台缓冲区\r\n。因此,当我在终端中输入以下1 并按回车键时,计算机将该语句读取为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;
    }
  }
}

【问题讨论】:

  • 你从哪里学来的?是什么让你认为这是真的?当您实际尝试并记录调用read 的每个结果的值时,您得到了什么?你有什么问题?
  • 你为什么使用System.in.read()?你应该使用Scanner

标签: java


【解决方案1】:

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

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

您可能需要检查您正在使用的机器以及为该环境定义的行分隔符。详情请参考What are the differences between char literals '\n' and '\r' in 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

【讨论】:

    猜你喜欢
    • 2012-05-14
    • 2011-09-04
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多