2016-10-05 38 views
2

我試圖從用戶那裏獲得10個整數輸入。另外,我想在用戶輸入錯誤類型的數據(不是整數)時處理異常。但是,我在使用for循環& try/catch時遇到此問題。 例如,如果我在第4個數字處輸入String。我會得到這樣的結果:在Java中使用For循環時嘗試/捕捉問題

Type 1. integer: 15 
Type 2. integer: 152 
Type 3. integer: 992 
Type 4. integer: jj 
Invalid number 
Type 5. integer: Invalid number 
Type 6. integer: Invalid number 
Type 7. integer: Invalid number 
Type 8. integer: Invalid number 
Type 9. integer: Invalid number 
Type 10. integer: Invalid number 

Integers: [15, 152, 992] 

我不知道如何重新進入循環異常被捕獲後。

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Scanner input = new Scanner(System.in); 
    Integer integer; 
    List<Integer> integerList = new ArrayList<Integer>(); 
    for (int i = 1; i < 11; i ++) { 
     System.out.print("Type " + i + ". integer: "); 
     try { 
     integer = input.nextInt(); 
     integerList.add(integer); 
     } 
     catch (InputMismatchException exc) { 
      System.out.println("Invalid number"); 
     } 

    } 
    System.out.println("Integers: " + integerList); 
} 
+0

究竟什麼是您發佈與輸出的問題?什麼是問題? – EJP

+1

首先您需要創建一個MCVE:http://stackoverflow.com/help/mcve然後,您需要重置掃描儀緩衝區:http://stackoverflow.com/questions/10604125/how-can-i-clear-the -scanner-buffer-in-java最後,您需要重置'i',以便重試相同的輸入。 –

回答

0

您不會將for循環留在異常處。而不是for循環,我建議使用while循環,例如

// your code 
while (integerList.size() < 10) { 
    Scanner input = new Scanner(System.in); 
    // your code 
    try { 
    // your code 
    } 
    catch (InputMismatchException exc) { 
     input.nextLine(); 
     // your code 
    } 
    // your code 
} 
// your code 
+1

它仍然不能解決我的問題。出於某些原因,異常語句被捕獲爲下一個Integer的輸入。 使用while循環在這裏創建了一個不定式循環。我的異常處理參數有什麼問題嗎? –

+0

@HieuCao在錯誤消息之前添加'input.nextLine()'到你的catch塊(請參閱http://stackoverflow.com/a/25277332/584862) – mre

+1

謝謝,它現在可以工作,即使使用for循環:) –

-1

或者當有異常計數時減少計數器,這樣就不會計數週期。

catch (InputMismatchException exc) { 
      System.out.println("Invalid number"); 
      i--;  
} 
-1

你要清楚掃描儀輸入:

import java.util.Scanner; 
import java.util.List; 
import java.util.ArrayList; 
import java.util.InputMismatchException; 

class foo { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     Scanner input = new Scanner(System.in); 
     Integer integer; 
     List<Integer> integerList = new ArrayList<Integer>(); 
     for (int i = 1; i < 11; i ++) { 
      System.out.print("Type " + i + ". integer: "); 
      try { 
       integer = input.nextInt(); 
       integerList.add(integer); 
      } 
      catch (InputMismatchException exc) { 
       System.out.println("Invalid number"); 
       input.nextLine(); 
       --i; 
      } 
     } 
     System.out.println("Integers: " + integerList); 
    } 
}