编辑 ExceptionSample 以便它可以捕获其中文本作为字符串输入而不是整数数据类型输入输入的异常

Edit ExceptionSample so it can catch exceptions wherein text is entered as String input instead of integer data type input

如果输入是字符串而不是整数,如何捕获异常? 这让我感到困惑,因为他们使用了 TryCatchFinally,这对我来说看起来很新。请赐教谢谢

import java.util.*;
public class ExceptionSample {
    public static void main (String[]args){
       Scanner s = new Scanner(System.in);
       int dividend, divisor, quotient;
       System.out.print("Enter dividend: ");
       dividend = s.nextInt();
       System.out.print("Enter divisor: ");
       divisor = s.nextInt();
       try {
        quotient = dividend/divisor;
        System.out.println(dividend + " / " + divisor + " = " + quotient);
       }
       catch (ArithmeticException ex) {
        System.out.println("Divisor cannot be 0.");
        System.out.println("Try again.");
       }
        finally  {
    System.out.println("Thank you.");
    }
    }
}

它会是这样的:

Scanner s = new Scanner(System.in);

int dividend, divisor, quotient;
while (true) {
    System.out.print("Enter dividend: ");
    try {
        dividend = s.nextInt();
    } 
    catch (java.util.InputMismatchException ex) {
        System.out.println("Invalid Dividend Entry! Try again...\n"); 
        s.nextLine(); // consume the Enter Key Hit.
        continue;
    }
    break;
}
    
while (true) {
    System.out.print("Enter divisor: ");
    try {
        divisor = s.nextInt();
        if (divisor == 0) {
            throw new java.util.InputMismatchException();
        }
    }
    catch (java.util.InputMismatchException ex) {
        System.out.println("Invalid Divisor Entry! Try again...\n"); 
        s.nextLine(); // consume the Enter Key Hit.
        continue;
    }
    break;
}
    
try {
    quotient = dividend / divisor;
    System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
    System.out.println("Divisor cannot be 0.");
    System.out.println("Try again.");
}
finally {
    System.out.println("Thank you.");
    s.close();
}

当使用 Scanner#nextInt() 方法并提供一个或多个字母字符时,将抛出 InputMismatchException。我们捕获此异常并利用它来验证数字输入。