我正在创建一个程序,它获取用户的信息并输出最小值、最大值、平均值、总和,并计算其中有多少值。我真的很难弄清楚如何创建 100 个项目的默认构造函数以及用户应该定义的数组大小。
创建一个新的数据集对象。创建对象的客户端指定可以添加到集合中的最大项目数。(用一个 int 参数编写一个构造函数。)
还要编写一个默认构造函数,它创建一个能够处理 100 个项目的 DataSet。
将整数数据项添加到 DataSet。如果已将最大数量的项目添加到集合中,则简单地忽略该项目。
这是我的代码
import javax.swing.*;
import java.util.*;
public class DataSet {
private int count; // Number of numbers that have been entered.
private double sum; // The sum of all the items that have been entered.
private double min;
private double max;
//Adds numbers to dataset.
public void addDatum(double num) {
count++;
sum += num;
if (count == 1){
min = num;
max = num;
} else if (num < min){
min = num;
} else if (num > max){
max = num;
}
}
public boolean isEmpty()
{
if(count == 0)
{
return true;
}
else
{
return false;
}
}
//Return number of items entered into the dataset.
public int getCount() {
return count;
}
//Return the sum of all the numbers that have been entered.
public double getSum() {
return sum;
}
//Return the average of all the numbers that have been entered.
public double getAvg() {
return sum / count;
}
//return Maximum value of data entered.
public double getMax(){
return max;
}
//return Minimum value of data entered.
public double getMin(){
return min;
}
public static void main (String[] args){
Scanner scanner = new Scanner(System.in);
DataSet calc = new DataSet();
double nextnumber = 0;
while (true){
System.out.print("Enter the next number(0 to exit): ");
nextnumber = scanner.nextDouble();
if (nextnumber == 0)
break;
calc.addDatum(nextnumber);
}
System.out.println("Min = "+calc.getMin());
System.out.println("Max = "+calc.getMax());
System.out.println("Mean = "+calc.getAvg());
System.out.println("Count = "+calc.getCount());
System.out.println("Sum = "+calc.getSum());
}
} //end class DataSet