2017-03-16 54 views
-3

我正在为异常处理大学的任务。我写了一些代码,但它不工作,只是想知道是否有人可以发现我要去哪里错了?任何帮助将不胜感激。高校分配的异常处理

我已经编写了一个专门用于处理InputMismatchException的类,但是,当我在数组中输入double而不是整数时,程序仍然崩溃,而不是像我希望的那样处理异常。

谢谢。

public class Lab8 { 
    public static void main(String[] args) { 
     ArrayList<Integer> a = new ArrayList<Integer>(); 
     Scanner s = new Scanner(System.in); 
     boolean x = true; 
     while (x == true) { 
      try { 
       System.out.println("Enter the next integer: "); 
       /*Autoboxing takes place here. The primitive type "int" taken in from the 
       user is converted to an Integer object.*/ 
       Integer i = s.nextInt(); 
       a.add(i); 
      } catch (InputMismatchException e) { 
       System.out.println("You must enter an integer."); 
      } 

      System.out.println("Would you like to enter another integer? (Y/N): "); 
      char y_n = s.next().charAt(0); 
      if (y_n == 'Y') { 
       x = true; 
      } else { 
       x = false; 
      } 
     } 
     for (int i = 0; i < a.size(); i++) { 
      System.out.println(a.get(i)); 
     } 

    } 
} 
+2

这听起来像应用程序正在提高,你是不是捕捉另一个异常,你总是可以使用异常,而不是InputMismatchException时,将捕获所有异常。 – SPlatten

+2

当您在调试器中逐步完成此操作时,抛出的异常是什么以及将哪一行抛出? – David

回答

0

只需添加

s = new Scanner(System.in); 

这样

System.out.println("Would you like to enter another integer? (Y/N): "); 
s = new Scanner(System.in); 
char y_n = s.next().charAt(0); 
0

由于扫描仪无法从输入拉一个int,它仍然卡在那里。在寻找新的东西之前,你需要清除输入;否则next.charAt(0)将成为double的第一个数字(在你的例子中)。在你的catch子句,添加

s.next();