我正在练习异常处理,并或多或少地掌握了基本概念.
我一直在寻找如何通过提示用户输入满足特定条件的值来继续执行的方法,尽管通过使用循环捕获了异常
我有这个特定的代码,要求用户输入一个范围之间的值,并具有异常处理以捕获是否正在输入字符串.但是,该程序在打印出异常处理后停止执行.
有什么想法可以实现异常处理后可以继续执行程序的循环或任何其他方法?
Scanner scanner = new Scanner(System.in);
int num = 0;
try
{
System.out.print("Please enter a number between 1 to 50 : ");
num = scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("Not a number");
return;
}
while (num > 50 || num < 1) {
System.out.print("Out of range. Enter a number between 1 to 50 : ");
num = scanner.nextInt();
}
System.out.println("The number is : " + num);
解决方法:
用这个:
Scanner scanner = new Scanner(System.in);
boolean isInputValid = false; // input flag, valid = true / invalid = false
int num = 0;
while(!isInputValid) {
try
{
System.out.print("Please enter a number between 1 to 50 : ");
num = scanner.nextInt();
// Input is a valid integer
if (!(num > 0 && num < 51)) { // input out of range
System.out.print("Out of range.");
}
else
isInputValid = true; // input valid, proceed & break loop
}
catch (InputMismatchException ex) { // input not an integer
System.out.println("Not a number");
scanner.next();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("The number is : " + num);
标签:exception,java
来源: https://codeday.me/bug/20191119/2034869.html