Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert command line arguments to a double array for calculating sums?

Tags:

java

So currently I get a "Sum = 0.0" and a Mean equals "NaN", after fighting a lot of messages that warned agains a "possible lossy conversion from double to int". I think the code is finally taking doubles, but still does not do what I would like it to: take values from the command line, place them into an array, sum these and then calculate the mean.

Any ideas where the errors lie?

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());
    }

}
like image 917
Mehmet Avatar asked Oct 19 '22 20:10

Mehmet


1 Answers

Instead of

this.marks = new double[0];

use

this.marks = marks;

You are currently assigning the marks member variable to be a zero-length array rather than the parameter, so the sum of the elements is zero, and marks.length is zero, so calSum()/marks.length is 0.0 / 0.0, which is defined to be NaN.

like image 99
Andy Turner Avatar answered Oct 21 '22 11:10

Andy Turner