如何将命令行参数转换为双精度数组以计算总和?

5

目前我得到的是"Sum = 0.0"和平均值为"NaN",在对抗很多警告信息后,这些信息警告可能会出现从double到int的损失转换。我认为代码最终采用了doubles,但仍然没有做到我想要的:从命令行获取值,将它们放入数组中,求和,然后计算平均值。

有任何想法错误出现在哪里吗?

public class StudentMarks{

protected double[] marks;
//create an array filled with double values

public StudentMarks(double[] marks){
    this.marks = new double[0]; //set the default array size    
    }

    public void setMarks(){
    this.marks = marks;
    }

    public void getArray(){
        //one can only  print arrays using loops.. 
        //took me a little to realise that erm. 

        for(int i=0; i<marks.length; i++)
        System.out.println(marks[i]);
    }

    public double calSum(){

    double totals = 0.0;

    for(double i: marks) {
        //double mLength = Double.parseDouble(marks[i]);
        totals+= i;     
    }
        return totals;
    }

    //A method to calculate the mean of all elements

    public double calMean(){
        double means = (calSum()/marks.length);
        return means;
    }

    //A main method to test

    public static void main(String[] args) {
        // Check to see if the user has actually sent a paramter to the method
        if (args.length != 7){
            System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
            System.exit(-1);
        }

        double[] prompt = new double[args.length];
        for (int i =0; i<args.length; i++){
            prompt[i] = Double.parseDouble(args[i]);
        }
        StudentMarks test = new StudentMarks(prompt);


        test.getArray();

        // Calculate the sum of all the values in the array and print it
        System.out.println("Sum: "+ test.calSum());

        // Calculate the mean of all the values in the array and print it
        System.out.println("Mean: "+ test.calMean());
    }

}

1
double[] prompt = new double[args.length]; 在此之前你检查了 if (args.length != 1) {...},因此它的长度总是为1。 - pzaenger
请定义您的输入格式。您说输入是一个双精度数组,但您只允许有一个命令行参数。请澄清。 - James Wierzba
我进行了小改动,允许从命令行输入更多数字,因此分隔符不是7。 - Mehmet
2个回答

3

不要使用

this.marks = new double[0];

使用

this.marks = marks;

目前,您正在将marks成员变量分配为长度为零的数组,而不是参数。因此元素的和为零,marks.length也为零,所以calSum() / marks.length等于0.0 / 0.0,这被定义为NaN


或者从构造函数中删除参数 double[] marks(如果您想保留标准初始化),并将 setMarks() 更改为 setMarks(double[] marks)(这就是 setter 方法应该工作的方式),并在您的 main() 方法中使用它。 - Lord M-Cube
@Mel 不用担心 - 如果答案有用的话,请考虑接受它。 - Andy Turner

0
一个问题出现在类的初始化器中。该类当前被初始化为长度为0的数组。相反,您应该使用输入来初始化它。
使用:
public StudentMarks(double[] marks){
    this.marks = marks;   
}

不要使用

public StudentMarks(double[] marks){
    this.marks = new double[0];    
}

这是代码的修复版本。请查看内联注释以获得更清晰的说明。
public class StudentMarks{

protected double[] marks;
//create an array filled with double values

//Pass in the array of marks to initialize the class
public StudentMarks(double[] marks){
    this.marks = marks; //set the marks array in the class to the passed in one   
}

//Set the class marks variable to the passed in one
public void setMarks(double[] marks){
    this.marks = marks;
}

//Change the name to "printMarks" to better reflect the purpose of the method
public void printMarks(){
    //one can only  print arrays using loops.. 
    //took me a little to realise that erm. 

    for(int i=0; i<marks.length; i++){
        System.out.println(marks[i]);
    }
}

//
public double calSum(){

    double totals = 0.0;

    for(double i: marks) {
        //double mLength = Double.parseDouble(marks[i]);
        totals+= i;     
    }

    return totals;
}

//A method to calculate the mean of all elements
public double calMean(){
    double means = (calSum()/marks.length);
    return means;
}

//A main method to test
public static void main(String[] args) {
    //Print out an error and exit only if we have less than 1 element passed in
    if (args.length != 7){
        System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
        System.exit(-1);
    }

    double[] prompt = new double[args.length];
    //Note that there is no error checking here
    for (int i =0; i<args.length; i++){
        prompt[i] = Double.parseDouble(args[i]);
    }

    //Initialize the StudentMarks class with the value of the input
    StudentMarks test = new StudentMarks(prompt);

    test.printMarks();

    // Calculate the sum of all the values in the array and print it
    System.out.println("Sum: "+ test.calSum());

    // Calculate the mean of all the values in the array and print it
    System.out.println("Mean: "+ test.calMean());
}

}

每当传递超过一个参数时,该应用程序都会崩溃。在您发布此帖子时,OP已将条件更新为!= 7; OP似乎对此有非常具体的要求。 - Andy Turner
感谢你的提示,@Andy Turner。在我编写代码时,OP仍然具有!=1,因此我做了一个假设并进行了更改。不过,你说得对,看起来他们有一个特定要求。我已经编辑了我的代码以符合该要求。 - Vel Genov
上面的代码实际上有几个问题。你现在删除了关于 length < 1 的内容吗?我倾向于避免发布大量的代码,因为它不太清楚你在语义上改变了什么(以及为什么改变),除了那个构造函数(你必须在页面上上下滚动来查看更改,不是很容易)。不要忘记,对你来说更清晰的东西并不一定对其他人阅读时也更清晰。 - Andy Turner
再次编辑以反映OP中的更改。我选择发布完整的代码是由于两个因素。首先,看起来OP是由一位新工程师编写的,我不确定指向一行代码是否会对他们有所帮助。这样他们就有一个可工作的代码片段可以进行比较。我的第二个原因是,代码中存在多个问题,现在已经消除了。尽管如此,我很感激批评,并将在未来记住这一点。 - Vel Genov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接