【发布时间】:2016-09-12 21:36:35
【问题描述】:
我正在创建一个接受用户输入的程序。现在我想在用户输入无效命令时重新运行输入选项。像这里只有整数输入是首选但如果用户输入文本,那么我想捕获异常并重新运行该方法。
我已经尝试过了,但它让我陷入了无限循环。实现这一目标的最佳方法是什么。如果有人在这方面帮助我,那就太好了。
boolean retry = true;
while(retry){
try{
//considering response from the user
System.out.print("\nEnter Your Command : ");
f_continue = processresponse(scanner.nextInt());
retry = false;
}catch(InputMismatchException e){
System.err.println("\nPlease Input a Valid Command from 1-5 or 0 for Exit");
}
}
【问题讨论】:
-
您可以在此处阅读有关处理扫描仪输入的更多信息:stackoverflow.com/questions/13102045/…
标签: java validation exception try-catch user-input