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());
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With