我正在尝试构建一个循环,当我在控制台中输入文本时,该循环执行特定的方法。 我想使用java.util.Scanner,但是当我尝试使用.hasNext()来检查if()内部,然后使用.next()来获取输入时,它一直等到我输入内容而不是循环播放。
while(true) {
main_loop();
}
private void main_loop() {
do_other_things();
if(sc.hasNext()){
System.out.println("user entered " + sc.next());
} else {
System.out.println("user entered nothing");
}
}
在输入内容之前,如何使其输出“用户无输入”,以便输出“用户输入[...]”,然后继续显示“用户无输入”?
答案 0 :(得分:1)
您需要运行一个单独线程以等待输入,然后(如果您希望在用户输入第二个字符串时触发此操作),则在处理完输入后,再次安排可运行对象
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
Scanner scanner = new Scanner(System.in);
Runnable runnable = new Runnable() {
@Override
public void run() {
if (scanner.hasNext()) {
String st = scanner.next();
//do something now the user has inputted
System.out.printf("The user entered a string! (%s)", st);
//run the runnable to wait again
executorService.schedule(this, 0, TimeUnit.SECONDS);
}
}
};
executorService.schedule(runnable, 0, TimeUnit.SECONDS);
}
答案 1 :(得分:0)
使用另一个线程:
public static void main(String[] args) {
new Thread(() -> {
Scanner scanner = new Scanner(System.in);
while (true) {
if (scanner.hasNext()) {
//... user has input
}
else {
//... user does not have input
}
}).start();
doSomethingElse();
}