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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26184409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:58:58  来源:igfitidea点击:

Java Console Prompt for ENTER input before moving on

java

提问by MasonAlt

I am creating a simply story, which will occasionally prompt the user to hit ENTER. It works the first time I prompt for it, but then it will immediately execute the other prompts, maybe because the program runs so fast by the time you let the ENTER key up, it already ran the check for the prompts.

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

Any ideas? Code Below.

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

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

采纳答案by M Anouti

The reason why System.in.readis not blocking the second time is that when the user presses ENTER the first time, two bytes will be stored corresponding to \rand \n.

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

Instead use a Scannerinstance:

而是使用一个Scanner实例:

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

回答by Bruno Franco

If we keep your approach of using System.in, the right thing to do is defining the bytes you will want to read, change your prompEnterKey to this:

如果我们继续使用 using 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();
        }
    }

It will work as you need. But, as the others said, you can try different approaches like the Scannerclass, that choice is up to you.

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