2013-09-26 373 views
2

該代碼假設在從輸入流中除以24提供的分母時捕獲異常。它需要捕捉異常,例如除以0,用戶輸入「hello」這樣的詞,或用戶可能輸入的任何其他奇怪的詞。另外,當輸入一個小數時,返回值必須是一個整數。如果發現任何異常,程序必須要求用戶輸入另一個整數,直到輸入一個有效的整數。整數除法(Java)的輸入異常

我遇到的問題是,該程序沒有捕捉到可能會輸入一個單詞或輸入小數的異常。我究竟做錯了什麼。

public class Division { 

    public int quotient(int numerator){ 
    boolean flag = false; 
    Scanner s = new Scanner(System.in); 
    int denom = 0;  
    while(flag==false){ 
     denom = Integer.parseInt(s.next()); 
     try{ 
      int q = numerator/denom; 
     } catch(NumberFormatException nfe){ 
      System.out.print("Enter an integer:"); 
      continue; 
     } catch(InputMismatchException ime){ 
      System.out.print("Enter an integer:"); 
      continue; 
     } catch(ArithmeticException ae){ 
      System.out.print("Enter a non-zero integer:"); 
      continue; 
     } 
     flag=true; 
    } 
    return numerator/denom; 
    } 

    public static void main(String[] args) { 
     System.out.print("Enter an integer (although you can make mistakes): "); 
     System.out.println("The quotient is " + new Division().quotient(24)); 
     System.out.println("Done!"); 
    } 

} 

回答

2

移動這一說法

denom = Integer.parseInt(s.next()); 

try/catch塊,使得它在NumberFormatException

try { 
    denom = Integer.parseInt(s.next()); 
    ... 
} catch (NumberFormatException nfe) { 
    System.out.print("Enter an integer:"); 
    continue; 
} catch (...) { 

閱讀抓到:The try block

+0

非常感謝!另外,如果我輸入一個小數,例如6.2,我希望它返回4作爲答案。但現在它認爲這是一個例外。我如何解決這個問題? – user2821523

+0

將變量類型更改爲「double」。將是一個很好的鍛鍊:) – Reimeus

+0

非常感謝。 – user2821523

1

您需要try{發生之前denom = Integer.parseInt(s.next());,而不是之後,這樣的例外實際上可以被逮住。

2

一個catch狀態只會捕獲內部的try區塊的異常。在try區塊內移動Integer.parseInt聲明。