2014-08-30 87 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; 
      }