2014-01-10 33 views
0

我正在編寫一個程序,它需要10個浮點數作爲輸入。但是,每當我輸入一個小數時,程序就會給我一個錯誤。我的問題是:如何編輯我當前的try-catch異常以僅捕獲字母等,並允許輸入小數(然後將它們存儲到數組中)。此外,無論這個問題,我的程序也是輸出的平均很多次,總是說,這是等於0編輯例外e來接收字母而不是小數

下面的程序:

import java.util.Scanner; 

公共類平均{

public static void main(String[] args) { 

    new Average().average(new double[10]); 
} 

public double average(double[] number) { 
    Scanner scanner = new Scanner(System.in); 

    int x = 0; 
    double sum = 0; 
    double[] numberList = new double[10]; //array to hold all numbers 
    double[] largerList = new double[10]; //array to hold numbers greater than the average 


    int numberIndex = 0; 
    int largerIndex = 0; 



    System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n"); 

    for (int i = 0; i < 10; i++) { 


     try { //try catch exception to catch decimal inputs as well as more /less than 10 integers 
      x = scanner.nextInt(); 
      sum += numberList[x]; //add up all inputs to find sum 
     } catch (Exception e) { 
      System.out.println("Invalid input! Please reenter 10 integer values."); 
      scanner = new Scanner(System.in); 
      i = -1; 
      numberIndex = 0; 
      largerIndex = 0; 
      numberList = new double[10]; 
      largerList = new double[10]; 
      continue; 
     } 
    } 

    for (int i = 0; i < number.length; i++) { 
     sum = sum + number[i]; 
     double average = sum/number.length; 

     //return average; 

     if (x > average) { 
      largerList[largerIndex] = x; //add negative input to negativeList array 
      largerIndex = largerIndex + 1; 

     } 
     System.out.println("Average value of your input is: " + average); 
     System.out.println(); 

    } 



    for (int i = 0; i < largerIndex; i++) { 
     System.out.println(largerList[i]); 
    } 
    return 0; 





} 

}

+0

你不指定'catch'哪個值,你只指定異常的類型。如果您只想在某些情況下拋出異常*(或不拋出),則必須根據需要安排代碼進行預測試,然後才能拋出異常。 –

回答

1

您正在使用nextInt()函數,該函數僅返回整數。 Ints不能包含小數。請查閱API並改爲查看nextFloat()和nextDouble()方法。

0

對於您的平均問題,您的打印語句將進入for循環,因此它將被執行number.length次。在循環外部移動打印語句。您還需要將平均變量的聲明放在循環之外。你也應該只需要循環來計算總和,你不需要每次計算平均值

double average; 
for(/*loop conditions*/) 
{ 
    sum = sum + number[i]; 
} 
average = sum/number.length; 
System.out.println("Average value of your input is: " + average); 
System.out.println();