我想编写无限的 while 语句,每次用户只需按 Enter
时都会执行该语句。我知道的每个流读取器都会在用户在控制台中输入任何内容或按 Enter
两次时执行。
我想写这样的东西:
Console:
output 1 [enter have been pressed onse]
output 2 [enter have been pressed onse]
output 3 [enter have been pressed onse]
[so on...]
这是我当前的代码:
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;
}
}
最佳答案
为了等待用户按下回车键,我通常会做类似的事情
new Scanner(System.in).nextLine();
演示:
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.");
}
}
输出:
Press enter.
[enter]
Thanks.
<小时/>
关于您的编辑,我仍然建议您使用扫描仪
。 (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
}
关于java - 如何编写当用户仅按 Enter 时执行的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9702849/