我的主程序将创建一个DataSet对象,读入值并调用addValue实例方法,直到遇到负值。然后它将调用getAverage和getStandardDeviation方法并打印出返回结果。平均值是3.28 标准差为1.972815247 这是我的代码。我现在基本上被卡住了。
import java.util.Scanner;
public class DataSet {
private double value;
private double count;
private double sum;
private double sumofSquares;
public void addValue(double value) {
while (value >= 0) {
count++;
sum += value;
sumofSquares += (value * value);
}
}
public double getAverage() {
return sum / count;
}
public double getStandardDeviation() {
return Math.sqrt(((count * sumofSquares) - (sum * sum)) / (count * (count - 1)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Value");
double value = sc.nextDouble();
DataSet j1 = new DataSet();
j1.addValue(value);
System.out.println("The average of the value " + j1.getAverage());
System.out.println("The Standard Deviation of the value" + j1.getStandardDeviation());
}
}
答案 0 :(得分:0)
这段代码似乎有很多问题。首先,您的输入代码不在while循环中,因此您不会获取任何新值。其次,你的addValue函数在输入正值时调用一个无限循环,因为while循环将继续运行并添加到你的DataSet成员。
我已经重构了您的代码以使其更有意义,请询问您是否对任何特定领域有任何疑问。
import java.util.Scanner;
public class DataSet {
private double value;
private double count;
private double sum;
private double sumofSquares;
public int addValue(double value) {
if(value >= 0) {
count++;
sum += value;
sumofSquares += (value * value);
return 0;
}else{
System.out.println("The average of the value " + this.getAverage());
System.out.println("The Standard Deviation of the value " + this.getStandardDeviation());
return -1;
}
}
public double getAverage() {
return sum / count;
}
public double getStandardDeviation() {
return Math.sqrt(((count * sumofSquares) - (sum * sum)) / (count * (count - 1)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Values");
double value = 0;
DataSet j1 = new DataSet();
while(true){
value = sc.nextDouble();
if(j1.addValue(value) == 0){
//continue
}else{
return;
}
}
}
}