我正在练习异常处理,并且或多或少地掌握了基本概念。
我一直在寻找如何通过提示用户输入满足特定条件的值来继续执行,尽管使用循环来捕获异常
我有这个特定的代码,请求用户输入一个范围之间的值,并有一个异常处理来捕获一个字符串是否被输入。但是,程序在打印出异常处理后停止执行。
我是如何实现循环或任何其他方法可以在异常处理后继续执行程序的?
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);
答案 0 :(得分:3)
例外情况应该处理特殊情况,即您无法提前预测的情况。由于您肯定可以预期用户可能会输入无效输入,因此您可以处理该无效输入而无需任何异常处理:
Scanner scanner = new Scanner(System.in);
int num = 0;
while (num > 50 || num < 1) {
System.out.print("\nPlease enter a number between 1 to 50 : ");
while (!scanner.hasNextInt()) {
scanner.next(); // discard non-integer inputs
System.out.print("\nPlease enter a number between 1 to 50 : ");
}
num = scanner.nextInt();
}
System.out.println("You entered " + num);
示例输出:
Please enter a number between 1 to 50 : -1
Please enter a number between 1 to 50 : 53
Please enter a number between 1 to 50 : ff
Please enter a number between 1 to 50 : rr rr ff
Please enter a number between 1 to 50 :
Please enter a number between 1 to 50 :
Please enter a number between 1 to 50 : 13
You entered 13
请注意,此代码比使用异常处理的版本短得多。
答案 1 :(得分:0)
使用此:
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);