2014-03-19 281 views
0

下面的程序只是從控制檯讀取整數並將其打印回來。當輸入一個非int(如char或String)時,Scanner會拋出異常。我試圖處理'try-catch'塊中的異常,並繼續閱讀下一個輸入。在控制檯的第一個非int輸入之後,程序運行到無限循環。有人可以幫忙嗎?Java:爲什麼循環中的try-catch塊只執行一次?

public class ScannerTest { 
    static int i=1; 
    static Scanner sc; 
    public static void main (String args[]){ 
     sc = new Scanner(System.in); 
     while (i!=0){ 
      System.out.println("Enter something"); 
      go(); 
     }  
    } 
    private static void go(){ 
     try{ 
      i = sc.nextInt(); 
      System.out.println(i); 
     }catch (Exception e){ 
      System.out.println("Wrong input, try again"); 
     }    
    } 
} 
+1

除了其他問題,您需要在您的功能中輸入用戶輸入。 – devnull

+1

在try-catch塊中捕獲InputMidmatchException時[Infinite While While Loop]的可能重複(http://stackoverflow.com/questions/6612806/infinite-while-loop-when-inputmidmatchexception-is-caught-in-try-catch -block) – fgb

+0

是的,對不起。 – Siva

回答

2

當掃描器沒有重新廣告整數,它不會清除輸入緩衝區。假設輸入緩衝區包含「abc」,因爲這是您輸入的內容。對「nextInt」的調用將失敗,但緩衝區仍將包含「abc」。所以在循環的下一個循環中,「nextInt」將再次失敗!

在您的異常處理程序中調用sc.next()應通過從緩衝區中刪除不正確的標記來糾正問題。

+0

謝謝。我能否請知道你從哪裏得到這些信息?我無法在線找到Java SE7文檔。任何我缺少的東西? :) – Siva

+0

在掃描儀文檔中:「當掃描程序拋出InputMismatchException時,掃描程序不會傳遞導致該異常的標記,以便可以通過其他方法檢索或跳過該標記。」 http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html –

-1
As devnull said take the input from user everytime either in loop or in method,just change the loop to ..and it works fine 

1)

while (i!=0){ 
     sc = new Scanner(System.in); 
     System.out.println("Enter something"); 
     go(); 

    } 

2其他方式

private static void go(){ 
     try{ sc = new Scanner(System.in); 
      i = sc.nextInt(); 
      System.out.println(i); 
     }catch (Exception e){ 
      System.out.println("Wrong input, try again"); 
     }    
    } 
+0

您每次創建一個新的掃描儀? –

0

使用字符串:

import java.util.Scanner; 

public class ScannerTest { 

static int i = 1; 
static Scanner sc; 

public static void main(String args[]) { 
    sc = new Scanner(System.in); 
    while (i != 0) { 
     System.out.println("Enter something"); 
     go(); 
    } 
} 

private static void go() { 
    try { 
     i = Integer.parseInt(sc.next()); 
     System.out.println(i); 
    } catch (Exception e) { 
     System.out.println("Wrong input, try again"); 
    } 
} 
}