Java 如何编写当用户仅按 Enter 时执行的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9702849/
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-16 06:26:05  来源:igfitidea点击:

How to write method which performs when user presses only Enter?

javainputconsole

提问by Pavel

I want to write infinity while statement which will perform every time when user just presses Enter. Every stream readers I know perform when user enteres anything into console or presses Entertwice.

我想编写无穷大的 while 语句,该语句将在用户每次按下时执行Enter。当用户在控制台中输入任何内容或按Enter两次时,我知道的每个流阅读器都会执行。



I want to write something like this:

我想写这样的东西:

Console:
output 1 [enter have been pressed onse]
output 2 [enter have been pressed onse]
output 3 [enter have been pressed onse]
[so on...]

控制台:
输出 1 [输入已被按下]
输出 2 [输入已被按下]
输出 3 [输入已被按下]
[等等...]

This is my current code:

这是我当前的代码:

addQuestionsInArray();

Random r = new Random();
DataInputStream is = new DataInputStream(System.in);
while (true) {
    String question = questionsList.get(r.nextInt(questionsList.size()));
    System.out.println(question);
    if (String.valueOf(is.readInt()).equals("0")) {
        break;
    }
}

采纳答案by aioobe

To wait for the user to hit enter, I usually do something like

为了等待用户按回车键,我通常会做类似的事情

new Scanner(System.in).nextLine();

Demo:

演示:

import java.util.Scanner;

class Test {
    public static void main(String[] args) {
        System.out.println("Press enter.");
        new Scanner(System.in).nextLine();
        System.out.println("Thanks.");
    }
}

Output:

输出:

Press enter.
[enter]
Thanks.


Regarding your edit, I still suggest you use a Scanner. (DataInputStreamshould be used for binary data, not strings and characters written on System.in):

关于您的编辑,我仍然建议您使用Scanner. (DataInputStream应该用于二进制数据,而不是写在 上的字符串和字符System.in):

Scanner s = new Scanner(System.in);

while (true) {
    String question = questionsList.get(r.nextInt(questionsList.size()));
    System.out.println(question);

    String input = s.nextLine();
    // int input = s.nextInt();    if you want integers

    if (input.equals("0"))
        break;

    // if (input == 0) break;      if you want integers
}

回答by Pavel

You would be looking for an action listenerin this case.

在这种情况下,您将寻找一个动作侦听器

Here'sanother SO question that addresses action listeners and the enter key.

这是另一个解决动作侦听器和回车键的 SO 问题。

回答by Sam

You can define a Threadthat with specify timing interval check user input with System.in.read()statement and if equals with Enter character /n/rterminate main loop

您可以定义一个Thread指定时间间隔检查用户输入的System.in.read()语句,如果等于Enter character /n/r终止主循环