我一直在尝试使用try / catch语句代替多个if语句,以便捕获用户的错误输入。除以0捕获按预期工作,但字母而不是数字捕获将不会继续通过for循环。
import java.util.Scanner;
public class Run1 {
public static final int its = 4;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numerator, denominator;
System.out.println("Enter the numerator");
numerator = keyboard.nextInt();
for (int i = 0; i < its; i++) {
try {
System.out.println("Enter the denominator ");
denominator = keyboard.nextInt();
System.out.println("numerator/denominator = " + numerator / denominator);
} catch (java.lang.ArithmeticException e) {
System.err.println("Don't divide by zero!");
//i -= 1;
} catch (java.util.InputMismatchException e) {
System.err.println("Enter a number!");
//i -= 1;
}
}
}
}
当一个字母作为分母输入时,循环如何加速,但是当抛出零捕获时不是这样?
答案 0 :(得分:4)
当您的代码抛出InputMismatchedException
时,您输入的字母尚未从输入流中删除。你的循环执行但它尝试再次读取相同的字母(总共3次)然后退出,因为你有限的东西到4次迭代。
检测到错误后,您需要丢弃当前输入行。
} catch (java.util.InputMismatchException e) {
System.err.println("Enter a number!");
keyboard.nextLine();
}
这就是我不喜欢在输入流上使用扫描仪的原因。我的偏好是将整行读入缓冲区然后在那里处理。
答案 1 :(得分:0)
您可以使用denominator = keyboard.nextLine();
代替denominator = keyboard.nextInt();
然后将String转换为整数。
答案 2 :(得分:0)
import java.util.Scanner;
public class Run1 {
public static final int its = 4;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numerator, denominator;
String num, den;
for (int i = 0; i < its; i++) {
try {
System.out.println("Enter the numerator");
num = keyboard.nextLine();
System.out.println("Enter the denominator ");
den = keyboard.nextLine();
numerator = Integer.parseInt(num);
denominator = Integer.parseInt(den);
System.out.println("numerator/denominator = " + (float)numerator / denominator);
} catch (java.lang.ArithmeticException e) {
System.err.println("Don't divide by zero!");
} catch (java.util.InputMismatchException e) {
System.err.println("Enter a number!");
} catch (java.lang.NumberFormatException e) {
System.err.println("Enter a number!");
}
}
}
}