Java控制台在继续之前提示输入ENTER [英] Java Console Prompt for ENTER input before moving on

查看:635
本文介绍了Java控制台在继续之前提示输入ENTER的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

任何想法?代码如下。

    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

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

而是使用扫描仪实例:

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

这篇关于Java控制台在继续之前提示输入ENTER的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆