【发布时间】:2020-09-12 19:41:34
【问题描述】:
我有一个单独的线程类,下面是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 块并按预期执行其中的行。一旦 catch 块的执行完成,它将再次迭代并请求键盘输入。但是当我尝试输入一个值(数字或字符)时,它不会读取任何内容并继续等待而不执行下一行。 我想要做的是,要求用户输入一个数字,如果用户输入一个字符,则在控制台中打印一条错误消息并再次迭代 while 循环。我该如何解决这个问题?提前致谢!
【问题讨论】:
-
请澄清您的问题。
But when I try to enter a value (even a number)...触发问题的值是什么?...keep waiting without executing the next lines所以卡在哪一行。你认为它与异常有什么关系?尝试减少您的代码,如How to create a Minimal, Reproducible Example。 -
如果用户输入字符而不是数字,则应触发异常。触发异常后会出现问题。如果我输入一个字符(比如说“q”),它会触发异常并执行 catch 块。然后它将再次迭代并等待用户输入(我添加了评论)。如果我输入正确的值(一个数字),它应该执行其余的行。但不执行其余代码,它会等待@IvoMori
标签: java multithreading exception