java – 如何将命令行参数转换为double数组以计算总和?

所以目前我得到一个“Sum = 0.0”和一个Mean等于“NaN”,在对很多消息进行了反击之后再次警告“可能从double转换为int”.我认为代码最终会占用双倍,但仍然没有按照我的意愿行事:从命令行获取值,将它们放入数组中,对它们求和,然后计算均值.

错误所在的任何想法?

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; istem.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 stem.exit(-1);
        }

        double[] prompt = new double[args.length];
        for (int i =0; iculate 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());
    }

}
最佳答案
代替

this.marks = new double[0];

使用

this.marks = marks;

您当前正在将marks成员变量指定为零长度数组而不是参数,因此元素之和为零,而marks.length为零,因此calSum()/ marks.length为0.0 / 0.0,其中被定义为NaN.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...