微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/java/437239.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐