2017-09-17 9 views
0

私が作成しようとしているのは、任意の数の入力を取る平均化プログラムです。これまでは、ユーザーに平均数を指定させる必要があり、多くの数値を指定しないとプログラムがクラッシュすることがありました。私は彼らが望むだけ多くの数字を入れさせることができる方法はありますか?その後、配列の長さは設定されていますか?ここで 任意の数の入力を持つJavaの平均プログラム

は、私が今使っているコードです:

import java.util.*; 

public class Average_any 
{ 
    public static void main (String[] args) { 
     Scanner scan = new Scanner (System.in); 

     System.out.println ("How many numbers do you want to enter?"); 

     final int ARRAY_LENGTH = scan.nextInt(); 

     System.out.println ("Please type the numbers you want to find the average of, " 
          + "and then type \"Done\"."); 
     System.out.println ("Warning: Only type the exact amount of numbers that you specified."); 
     // If user doesn't enter same number, results in crash 
     double[] numbers = new double [ARRAY_LENGTH]; 
     do { 
      for (int i = 0; i < numbers.length; i++) { 
       while (!scan.hasNextInt()) { 
       System.out.println("That's not a number!"); 
       scan.next(); //Need this to enter another input 
       } 
       numbers[i] = scan.nextInt(); 
      } 
     } while (!scan.hasNext("Done")); 

     double total = 0; 
     for (int i = 0; i < numbers.length; i++) { 
      total += numbers[i]; 
     } 

     double average = total/ARRAY_LENGTH; 

     System.out.println ("Your average is: " + average); 
    } 
} 

(念のために誰もが疑問に思っている、私たちは学校での簡単なバージョンをしたのでありません、これは学校の割り当て、私は思っていたされていません)

+0

完全方程式のうちの配列を取るあなたは 'List'のことを聞いたことがありますか? –

+0

いいえ、申し訳ありませんが、HTMLとCSS以外のコーディングに少し新しくて – Owen

+0

(これは少し修辞的な質問でした。リストにいくつかの調査をしてほしいと本当に示唆していました) –

答えて

1

Scanner scan = new Scanner (System.in); 
double total = 0; 
int count = 0; 

while (scan.hasNextDouble()) { 
    total += scan.nextDouble(); 
    count ++; 
} 
double average = total/count; 
+0

ありがとう、これは、配列やリストを使うよりもずっと速いです – Owen

関連する問題