我有一个单独的线程类,下面是 run 方法,
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
int iRequestType = 0;
int iRequestId = 0;
while (!exit){
try {
System.out.print("\nRealTime - 1\nHttpUrl - 2\nSelect one : ");
iRequestType = scanner.nextInt(); //it will wait here after the exception occurs
System.out.print("\nEnter Request ID : ");
iRequestId = scanner.nextInt();
if(iRequestType == 1 && !map_RealTimeRequests.isEmpty()){
sendRealTimeRequest(iRequestId);
} else if (iRequestType == 2 && !map_HttpUrlRequests.isEmpty()){
sendHttpUrlRequest(iRequestId);
} else if(iRequestType > 2) {
System.out.println("Invalid List Number");
}else {
System.out.println("Empty List");
}
} catch (InputMismatchException e){
System.out.println("Invalid request type or ID : " + e);
scanner.close();
scanner = new Scanner(System.in);
}
}
}
如果我输入数字,程序就可以正常工作。当我输入一个字符时,它会转到 catch block 并按预期执行其中的行。一旦 catch block 执行完成,它将再次迭代并请求键盘输入。但是当我尝试输入一个值(数字或字符)时,它不会读取任何内容并继续等待而不执行下一行。 我想要做的是,要求用户输入一个数字,如果用户输入一个字符,则在控制台中打印一条错误消息并再次迭代 while 循环。我该如何解决这个问题?提前致谢!
最佳答案
您不应该调用scanner.close()
,因为这会关闭System.in
。您不想关闭 System.in,您只是想清除缓冲区。您可以像以前一样通过更换扫描仪来实现这一点(无需 close() 调用),或者如果是单行输入,则可以调用 nextLine()
,如下所示:
} catch (InputMismatchException e){
System.out.println("Invalid request type or ID : " + e);
scanner.nextLine();
}
关于java - Java中一旦线程抛出异常,扫描器就不会读取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62014762/