2017-03-20 48 views
-3

我有一個嘗試捕獲,是爲了捕捉任何不是一個整數。當我輸入一個非整數(例如5.6)時,它告訴我只有整數是允許的,並讓我再試一次(因爲它應該)。但是,如果我再次輸入一個非整數,它不會說出任何內容,並會繼續輸入,從而使輸出保持空白。Try-catch只有循環一次

if (choicesObjects == b) { 
    System.out.println("TEST 2");    
    System.out.println("Object: Right triangle"); 
    System.out.println("\nEnter length of Right triangle: "); 

    int lengthOfTriangle = 0; 
    try {     
     lengthOfTriangle = input.nextInt();   
    } catch(InputMismatchException e) {   
     System.out.println("\nError: user input must be an integer greater than 0.\n"); 
     System.out.println("Object: Right triangle"); 
     System.out.println("\nEnter length of Right triangle: "); 
     input.next();     
    } 
    //method stuff 
} 
+5

的try/catch不是一個循環。如果你想循環,你需要使用循環。 –

+0

而你的問題是... –

+0

你需要做這樣的事情:while(condition not met){獲得用戶輸入} – ndlu

回答

4

try/catch聲明不是循環。它將始終執行一次。

當然,如果try塊內有一個循環,該塊將繼續執行直到終止。但是這種循環需要使用明確的命令,如whilefor

顯然當輸入一個非整數值(例如5.6)時會發生什麼,是nextInt()語句拋出一個異常並進入catch塊。如果提供了方法的完整代碼,則可以給出更好的解釋。

3

爲此,您可以定義一個函數,這樣的事情應該工作

private int getNextInt(Scanner input) { 
    boolean isInt = false; 
    int userInput; 
    while(!isInt) { 
     try { 
      userInput = Integer.valueOf(input.next()); 
      isInt = true; 
     } catch(NumberFormatException e) { 
      // Do nothing with the exception 
     } 
    } 
    return userInput; 
} 

這應該運行,直到給定的輸入是一個int,然後返回表示INT

+1

您也必須在捕獲中使用無效標記,否則它將陷入無限循環。見[這裏](http://stackoverflow.com/questions/3572160/how-to-handle-infinite-loop-caused-by-invalid-input-using-scanner) –

+0

@shashwat好點,修復 – Mikenno

+0

@Mikenno你得到了補償......老實說:刪除不太好的答案是很好的做法。 P1只是爲了做到這一點! – GhostCat

1

您可以更新您的代碼的東西這樣的 -

Scanner in = new Scanner(System.in); 
    int num = 0; 
    while(true) { 
     try{ 
      num = in.nextInt(); 
      break; 
     }catch(Exception e){ 
      //print statements 
      System.out.println("Try again"); 
     } 
    } 
    System.out.println("Done"); 
+0

你測試過嗎?因爲這不適合我[這裏](https://ideone.com/hHktSE)。只是卡在一個無限循環,印刷'再試一次' –

+0

是的,@Shashwat。我確認了上述代碼的執行情況。 –

+0

檢查我剛剛給的鏈接 –

1

像這樣

布爾檢查= true;

而(檢查){ 如果choicesObjects == B {

輸入代碼here`的System.out.println( 「TEST 2」); System.out.println(「Object:Right triangle」); System.out.println(「\ n輸入直角三角形的長度:」);

  int lengthOfTriangle = 0; 

      try { 

      lengthOfTriangle = input.nextInt(); 


      } catch(InputMismatchException e) { 

       System.out.println("\nError: user input must be an integer greater than 0.\n"); 
       check = false; 

的System.out.println( 「對象:直角三角形」);的System.out.println( 「直角三角形的\ n輸入長度:」); input.next();

  } 
       //method stuff 
      } 
     } 

`

+0

您必須在捕獲中使用無效令牌。檢查[這裏](http://stackoverflow.com/questions/3572160/how-to-handle-infinite-loop-caused-by-invalid-input-using-scanner) –

+0

請花一些時間來格式化您的答案。這是一團糟。 –

+0

userInput = Integer.parseInt(input.next()); – demopix