Così attualmente ricevo un "Sum = 0.0" e una Media equivale a "NaN", dopo aver combattuto un sacco di messaggi che avvisavano di nuovo una "possibile perdita di conversione da double a int". Penso che il codice stia finalmente prendendo il doppio, ma ancora non fa quello che mi piacerebbe: prendere i valori dalla riga di comando, metterli in una matrice, sommarli e quindi calcolare la media.Come si convertono gli argomenti della riga di comando in un doppio array per il calcolo delle somme?
Qualche idea in cui si trovano gli errori?
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());
}
}
'double [] prompt = new double [args.length];' avrà sempre la lunghezza 1 in quanto si controlla se '(args.length = 1!) {...}' a destra prima. – pzaenger
Si prega di definire il formato di input. Dici che l'input è una matrice di doppi, eppure permetti solo che ci sia un argomento a riga di comando. Si prega di precisare. –
Ho apportato una modifica minore consentendo di immettere più numeri dalla riga di comando, quindi la delimitazione non è 7 – Mehmet