2014-08-30 104 views
0

为什么输出继续运行?当我运行这个程序,并且在输出中输入时,它会一直运行,并且不会让我输入更多数字。这是为什么发生?输出继续运行

import java.util.InputMismatchException; 
import java.util.Scanner; 

public class ExceptionTest2 
{ 

    public static void main(String[] args) 
    { 
     Scanner st = new Scanner(System.in); 
     int ab, bd, cde; 
     ab = bd = cde = 0; 
     boolean infinite, in; 
     do 
     { 
      System.out.println("Enter the numbers to divide"); 
      infinite = false; 
      in = true; 
      try 
      { 
       ab = st.nextInt(); 
       bd = st.nextInt(); 
       infinite = false; 
       in = true; 
      } 
      catch (InputMismatchException e) 
      { 
       System.out.println("Invalid input"); 
       in = true; 
      } 
      finally 
      { 
       if (in) 
       { 
        try 
        { 
         System.out.println("I am in try block before exception"); 
         cde = ab/bd; 
         System.out.println("I am in try block after exception"); 
        } 
        catch (Exception e) 
        { 
         infinite = true; 
        } 
        finally 
        { 
         if (!infinite) 
         { 
          System.out.println("Answer is " + cde); 
         }; 
        } 
       } 
      } 
     } 
     while (cde != 100); 
     st.close(); 
    } 
} 
+0

哪条线继续运行?而且,将来它会显着帮助您使用更多的描述性变量名称。 – Zyerah 2014-08-30 06:10:59

+1

你输入了什么?也许'cde'从来没有100. – Henry 2014-08-30 06:13:31

+0

我只是跑这个,它对我来说很好(除了给我整数除法结果)。它允许我输入更多的数字来划分。你能给我们一个你的输入的例子,以及你得到的输出的例子吗? – therealrootuser 2014-08-30 06:21:17

回答

1

问题:

ab = st.nextInt(); 

当你输入就可以了String我不会得到由nextInt消耗,因此没有人会为您提供无限循环

解决方案:

你需要消耗那些字符您在catch块输入,以避免无限循环

样品S:

  catch (InputMismatchException e) { 
       System.out.println("Invalid input"); 
       st.nextLine(); 
       in=true; 
      }