2015-09-10 53 views
1

這是用於作業。程序在Java中處理異常後完成

我想創建一個程序,需要十個輸入數字的平均值。當用戶輸入不是數字的字符時,會捕獲NumberFormatException異常。該程序在異常被捕獲後完成,因此我將其更改爲使用遞歸在異常被捕獲後再次調用該方法,但現在它會打印多個平均值,其中一些不正確。

如何更改程序,使其在異常被捕獲而不是完成後繼續詢問輸入?捕捉異常後,我不希望程序結束。

import java.util.Scanner; 

import java.util.Scanner; 

public class PrintAverage { 

    int average; 

    public static void main(String args[]) { 
     System.out.println("You are going to enter ten numbers to find their average."); 
     getInput(); 
    } 

    private static void getInput() { 
     String input; 
     int sum = 0; 
     int[] arrayOfIntegers = new int[10]; 
     double average = 0; 
     Scanner scanner = new Scanner(System.in); 

     try { 
      for (int i = 0; i < arrayOfIntegers.length; i++) { 
       System.out.println("Enter the next number."); 
       input = scanner.nextLine(); 
       arrayOfIntegers[i] = Integer.parseInt(input); 
      } 
     } catch (NumberFormatException exception) { 
      System.out.println("The last entry was not a valid number."); 
      getInput(); 
     } 

     for (int k = 0; k < arrayOfIntegers.length; k++) { 
      sum = sum + arrayOfIntegers[k]; 
     } 
     average = sum/arrayOfIntegers.length; 
     System.out.println("The average is " + average); 

    } 
} 
+1

您可以考慮使用'Scanner.hasNextInt()'來驗證輸入是試圖解析它之前一個整數(使用'Scanner.nextInt ()')。 –

+0

不錯的一個!這裏的文檔:http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNextInt-- – pyb

+1

getInput()方法應該只做它的名字:Get輸入。請用另一種方法移動平均值計算,並在整數數組準備就緒時調用它。 – sanastasiadis

回答

3

你的try/catch不夠具體,所以它在詢問你想要的所有數字後會捕獲異常。

  1. 找出被拋出NumberFormatException的
  2. 移動你的try/catch周圍的線
  3. 存儲在臨時變量可以爲空輸入(原始INT不允許)
  4. 只要沒有設置爲合法號碼,請繼續詢問一個值(=只要它沒有設置爲合法號碼)
+0

這是一個很好的答案,它描述了一個解決方案的一般原理,並允許OP找出他們自己的編碼。 1+ –

+1

@HovercraftFullOfEels謝謝:-)如果我們只是發佈有效的代碼,我相信作業問題/答案在這裏幾乎沒有價值。 – pyb

+0

1. NumberFormatException應該由parseInt引發。 | 2.如果我從try塊中取出其他東西,那麼它將只是parseInt行。 |我還沒有弄清楚這個部分。 |我也必須弄清楚這一點。非常感謝你。 – EricGrahamMacEachern

1

本地化異常。 更改此:

try { 
     for (int i = 0; i < arrayOfIntegers.length; i++) { 
      System.out.println("Enter the next number."); 
      input = scanner.nextLine(); 
      arrayOfIntegers[i] = Integer.parseInt(input); 
     } 
    } catch (NumberFormatException exception) { 
     System.out.println("The last entry was not a valid number."); 
     getInput(); 
    } 

這樣:

for (int i = 0; i < arrayOfIntegers.length; i++) { 
     System.out.println("Enter the next number."); 
     input = scanner.nextLine(); 
     try { 
      arrayOfIntegers[i] = Integer.parseInt(input); 
     } catch (NumberFormatException exception) { 
      System.out.println("The last entry was not a valid number."); 
      i--; //so you don't lose one of the 10. 
     } 
    } 
+0

這將繼續循環,使arrayOfIntegers不完全初始化。 – pyb

+0

查看代碼更新。 (i--) –

+0

我不喜歡弄亂索引,因爲它使代碼更不可讀。我更喜歡沿線 'while(userInput == null){ 嘗試userInput = scanner.nextLine(); } catch(E){...} } doSomething(userInput); ' 我覺得更容易理解。 – pyb