2014-09-02 66 views
1

試圖在控制檯中輸入雙精度數組列表,然後當用戶用ctrl-z或d結束數組列表輸入時,找到它們輸入的數字列表的平均值雙打。JAVA:查找雙數組列表的平均值

我收到很多來自這個錯誤,我不知道爲什麼!

double sum = 0; 
for(double d : numbers) { 
    sum += d; 
} 
System.out.println(sum/numbers.size()); 
+3

你得到的錯誤究竟是什麼? – resueman 2014-09-02 18:37:12

+0

就行「Double input = in.nextDouble();」我得到一個類型不匹配的錯誤,它說「類型不匹配:不能從double轉換爲Double」 – seriallchiller 2014-09-02 18:48:31

回答

4

要計算最終的平均 任何和所有幫助表示讚賞到一個不起作用的變量定義。你雖然接近。只需在for循環外聲明變量sum即可。

double sum = 0; 
for (double element : numbers) { 
     sum += element; 
    } 
System.out.println(sum/numbers.size()); 

您也可能不希望每次打印出當前的平均值,因此您應該將其移至循環之後。

0
Double sum += element; 

這是不合法的語法,你想補充一點:因爲我是一個初學java

public static void main(String[] args) { 
    ArrayList<Double> numbers = new ArrayList<Double>(); 

    Scanner in = new Scanner(System.in); 

    while (in.hasNextDouble()) 
    { 
     Double input = in.nextDouble(); 
     numbers.add(input); 
    } 

    in.close(); 

    for (Double element : numbers) { 
     Double sum += element; 
     System.out.println(sum/numbers.size()); 
    } 
} 
1
// don't miss the imports 
import java.util.ArrayList; 
import java.util.Scanner; 

// you might have missed to add your main() method in a class 
public class Average { 
    public static void main(String[] args) { 
     // This part was ok 
     ArrayList<Double> numbers = new ArrayList<Double>(); 
     Scanner in = new Scanner(System.in); 
     while (in.hasNextDouble()) { 
      Double input = in.nextDouble(); 
      numbers.add(input); 
     } 
     in.close(); 

     // Forgot to initialize the value of sum 
     Double sum = 0d; 
     for (Double element : numbers) { 
      // add the element 
      sum += element; 
      // don't count the average here 
     } 
     // count it outside the loop 
     System.out.println(sum/numbers.size()); 
    } 
} 
0

我已經添加java.util這是需要在代碼中的主要問題是在你的for循環PLZ標記答案Scannercollections classes 包。謝謝:)

import java.util.*; 
    public class Test { 

     public static void main(String[] args) { 
      Double sum=0.0; 
       ArrayList<Double> numbers = new ArrayList<Double>(); 

       Scanner in = new Scanner(System.in); 

       while (in.hasNextDouble()) 
       { 
       Double input = in.nextDouble(); 
       numbers.add(input); 
       } 

       in.close(); 


       for (Double element : numbers) { 
        sum += element; 
      } 
        System.out.println(sum/numbers.size()); 

       } 

    }