Java 检查扫描仪在while循环中是否包含任何内容
如何检查Java 检查扫描仪在while循环中是否包含任何内容,java,while-loop,java.util.scanner,wait,Java,While Loop,Java.util.scanner,Wait,如何检查扫描器中的输入是否可用而无阻塞风险 例如,考虑下面的方法。在每个循环迭代中,如果有用户输入,它应该接受用户输入,但如果没有输入,则不进行输入。相反,reader.nextLine()会等待用户输入一行,然后再继续 public void creatureCombate() { while (true) { Scanner reader = new Scanner(System.in); String userInput = reader.next
扫描器中的输入是否可用而无阻塞风险
例如,考虑下面的方法。在每个循环迭代中,如果有用户输入,它应该接受用户输入,但如果没有输入,则不进行输入。相反,reader.nextLine()
会等待用户输入一行,然后再继续
public void creatureCombate() {
while (true) {
Scanner reader = new Scanner(System.in);
String userInput = reader.nextLine();
wait(1);
System.out.println("Wolf attacks");
if(userInput.equals("hit")){
System.out.println("hit wolf");
} else{
System.out.println("Tries again");
}
}
}
否,由于所有nextXxx()
和hastnextxxx()
方法都被阻塞,因此您不能“在未输入任何内容的情况下继续”
如果您希望在等待输入时执行代码(例如wolf攻击),则需要多个线程。您需要使用多个线程,并使主线程
等待输入完成或超时,例如:
public static void main(String[] args) throws Exception {
final List<String> input = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int count = 0;
while (count < 10) {
Runnable inputThread = () -> {
scanner.reset();
System.out.println("Enter input");
try{
String line = scanner.nextLine();
input.add(line);
}catch(Exception e){}
};
Thread t = new Thread(inputThread);
t.start();
Thread.currentThread().join(10000);
t.interrupt();
if(input.isEmpty()){
System.out.println("Nothing enteresd");
} else{
System.out.println("Entered :" + input.get(0));
input.clear();
}
count++;
}
scanner.close();
}
publicstaticvoidmain(字符串[]args)引发异常{
最终列表输入=新的ArrayList();
扫描仪=新的扫描仪(System.in);
整数计数=0;
同时(计数<10){
可运行输入线程=()->{
scanner.reset();
System.out.println(“输入”);
试一试{
字符串行=scanner.nextLine();
输入。添加(行);
}捕获(例外e){}
};
螺纹t=新螺纹(输入螺纹);
t、 start();
Thread.currentThread().join(10000);
t、 中断();
if(input.isEmpty()){
System.out.println(“无输入”);
}否则{
System.out.println(“输入:+input.get(0));
input.clear();
}
计数++;
}
scanner.close();
}
您的问题是……嗯,每次循环执行时是否有必要创建一个新的扫描对象?正如@JoeC所指出的,为什么这在你的案例中是个问题?我在上面的代码中没有发现问题?请提供有关问题的更多详细信息,而不是reader.nextLine()
,检查reader.hasNextLine()
,如果是真的,请仅调用nextLine()
。这是因为nextLine()input@Gus也将阻塞:此方法在等待输入时可能会阻塞。