在继续之前,Java控制台提示输入

我正在创建一个简单的故事,偶尔会提示用户按ENTER键。 它第一次提示它时工作,但它会立即执行其他提示,可能是因为当你按ENTER键时程序运行得如此之快,它已经检查了提示。

有任何想法吗? 代码如下。

System.out.println("...*You wake up*..."); System.out.println("You are in class... you must have fallen asleep."); System.out.println("But where is everybody?\n"); promptEnterKey(); System.out.println("You look around and see writing on the chalkboard that says CBT 162"); promptEnterKey(); ////////////////////////////////////////////////////// public void promptEnterKey(){ System.out.println("Press \"ENTER\" to continue..."); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } 

System.in.read第二次没有阻塞的原因是当用户第一次按下ENTER时,将存储对应于\r\n两个字节。

而是使用Scanner实例:

 public void promptEnterKey(){ System.out.println("Press \"ENTER\" to continue..."); Scanner scanner = new Scanner(System.in); scanner.nextLine(); } 

如果我们继续使用System.in的方法,正确的做法是定义您想要读取的字节,将prompEnterKey更改为:

  public static void promptEnterKey(){ System.out.println("Press \"ENTER\" to continue..."); try { int read = System.in.read(new byte[2]); } catch (IOException e) { e.printStackTrace(); } } 

它会按你的需要工作。 但是,正如其他人所说,你可以尝试不同的方法,如Scanner类,这个选择取决于你。