使用 try-catch 避免输入不匹配
InputMismatch Avoidance with try-catch
为了验证 int 输入,我看到了使用 InputMismatch 异常的 try-catch 用法。虽然输入一个字符串后,我只是让捕获代码块播放,然后我的程序由于不匹配而退出,但我想让用户重新输入。我在四处搜索后实现了一个布尔正确的 while 循环,但仍然没有成功。
int quantity = 0;
boolean correct = true;
while(correct){
try{
System.out.print("Input Quantity you would like to purchase: ");//Get quantity
quantity = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Input must be a number");
input.nextInt();//Get the input as a string
correct = false;
}
System.out.println("Quantity: " + quantity);
}
我之前只是使用了扫描仪内置的 hasNextInt,效果很好,但我想测试一下 try-catch。听说用try-catch,没听说用try-catch。我为什么要避免使用它?
这是修复方法,在 catch 中使用 input.nextLine();
,不要使 correct=false
while(correct){
try{
System.out.print("Input Quantity you would like to purchase: ");//Get quantity
quantity = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Input must be a number");
input.nextLine();
continue;
}
System.out.println("Quantity: " + quantity);
}
但就像其他人指出的那样,尽量不要将异常用于一般流程。仅将其用于跟踪不寻常的异常。所以,我不鼓励你使用这个代码。使用 input.hasNextInt()
代替
为了验证 int 输入,我看到了使用 InputMismatch 异常的 try-catch 用法。虽然输入一个字符串后,我只是让捕获代码块播放,然后我的程序由于不匹配而退出,但我想让用户重新输入。我在四处搜索后实现了一个布尔正确的 while 循环,但仍然没有成功。
int quantity = 0;
boolean correct = true;
while(correct){
try{
System.out.print("Input Quantity you would like to purchase: ");//Get quantity
quantity = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Input must be a number");
input.nextInt();//Get the input as a string
correct = false;
}
System.out.println("Quantity: " + quantity);
}
我之前只是使用了扫描仪内置的 hasNextInt,效果很好,但我想测试一下 try-catch。听说用try-catch,没听说用try-catch。我为什么要避免使用它?
这是修复方法,在 catch 中使用 input.nextLine();
,不要使 correct=false
while(correct){
try{
System.out.print("Input Quantity you would like to purchase: ");//Get quantity
quantity = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Input must be a number");
input.nextLine();
continue;
}
System.out.println("Quantity: " + quantity);
}
但就像其他人指出的那样,尽量不要将异常用于一般流程。仅将其用于跟踪不寻常的异常。所以,我不鼓励你使用这个代码。使用 input.hasNextInt()
代替