整数除法 (Java) 的输入异常



此代码应该在将 24 除以输入流中提供的分母时捕获异常。它需要捕获异常,例如除以 0 时,如果用户输入了"hello"之类的单词,或者用户可能输入的任何其他奇怪内容。此外,当输入小数时,返回值必须是整数。如果捕获到任何异常,程序必须要求用户输入另一个整数,直到输入有效的整数。

我遇到的问题是程序没有捕获可能输入单词或可能输入小数的异常。我做错了什么。

  public class Division {
  public int quotient(int numerator){
  boolean flag = false;
  Scanner s = new Scanner(System.in);
  int denom = 0;      
  while(flag==false){
      denom = Integer.parseInt(s.next());
      try{
          int q = numerator/denom;
      } catch(NumberFormatException nfe){
          System.out.print("Enter an integer:");
          continue;
      } catch(InputMismatchException ime){
          System.out.print("Enter an integer:");
          continue;
      } catch(ArithmeticException ae){
          System.out.print("Enter a non-zero integer:");
          continue;
      }
      flag=true;
  }
  return numerator/denom;
  }
  public static void main(String[] args) {
      System.out.print("Enter an integer (although you can make mistakes): ");
      System.out.println("The quotient is " + new Division().quotient(24));
      System.out.println("Done!");
  }
}

移动此语句

denom = Integer.parseInt(s.next());

进入try/catch块,使其被捕获在NumberFormatException块中

try {
    denom = Integer.parseInt(s.next());
    ...
} catch (NumberFormatException nfe) {
    System.out.print("Enter an integer:");
    continue;
} catch (...) {

阅读:尝试块

catch语句将仅捕获在其try启动的异常。将 Integer.parseInt 语句移动到try块内。

你需要try{发生在denom = Integer.parseInt(s.next());之前,而不是之后,这样异常才能被实际捕获。

最新更新