2017-03-28 85 views
0

這是我迄今爲止從我的代碼。這是一門入門課程,所以我們還沒有涉及更多高級課題。用我迄今爲止輸入的數字,然後按-1,但該程序沒有做任何事情。 我們並未覆蓋陣列。初學者在Java中使用OOP我該如何getAverage和getStandardDeviation()

import java.util.Scanner; 

public class DataSet { 
    private double value,count,sum, sumOfSquares, average; 

    public DataSet(double value) 
    { 
     this.value=value; 


    } 
    public double getAverage(){ 
    int value=0; 
    int count=0; 
    double sum=0; 
    while(value != -1){ 

     sum=sum+value; 
    average=sum/count; 

    } 
     return average; 
    } 
    public static void main(String[] args) 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter a numbers to get average and standard deviation: "); 
     int value=input.nextInt(); 

     DataSet s= new DataSet(value); 
     System.out.println(s.getAverage()); 
    } 



} 
+0

看到這個https://github.com/apache/mahout/blob/master/mr/src/test/java/org/apache/mahout/cf/taste/impl/common/RunningAverageAndStdDevTest.java –

回答

0

試試下面的程式。這個類只有一般的方法。您可以添加對arraylist值進行操作的任何數字方法。

import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 

public class DataSet { 

private List<Integer> values; 

public DataSet(List<Integer> values) { 
    this.values = values; 
} 

public double getAverage() { 
    int sum = 0; 
    double result = 0.0; 
    for (int value : values) { 
     sum = sum + value; 
    } 
    if (values.size() > 0) { 
     result = sum/values.size(); 
    } 
    return result; 
} 

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    List<Integer> values = new ArrayList<Integer>(); 
    System.out 
      .print("Enter a numbers to get average and standard deviation: "); 
    int value = input.nextInt(); 
    while (value != -1) { 
     values.add(value); 
     value = input.nextInt(); 
    } 
    DataSet s = new DataSet(values); 
    System.out.println(s.getAverage()); 
} 

}