2015-12-11 5 views
5

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

} 
+1

'double [] prompt = new double [args.length];' avrà sempre la lunghezza 1 in quanto si controlla se '(args.length = 1!) {...}' a destra prima. – pzaenger

+0

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. –

+0

Ho apportato una modifica minore consentendo di immettere più numeri dalla riga di comando, quindi la delimitazione non è 7 – Mehmet

risposta

3

Invece di

this.marks = new double[0]; 

uso

this.marks = marks; 

Si stanno definendo la variabile marks membro per essere una matrice di lunghezza zero invece del parametro, quindi la somma degli elementi è zero e marks.length è zero, quindi calSum()/marks.length è 0.0/0.0, che è definito come NaN.

+0

sei un salvatore! grazie – Mehmet

+0

Oppure rimuovi il parametro 'double [] marks' dal costruttore (se vuoi mantenere l'inizializzazione standard) e cambia' setMarks() 'in' setMarks (double [] marks) '(questo è il modo in cui i metodi setter dovrebbero funzionare comunque) e usarlo nel metodo 'main()'. –

+0

@Mel non preoccuparti - per favore considera di accettare la risposta se fosse utile. –

0

Un problema era nell'inizializzatore della classe. La classe è attualmente inizializzata su una matrice di lunghezza 0. Invece dovresti inizializzarlo con il tuo input.

Usa

public StudentMarks(double[] marks){ 
    this.marks = marks; 
} 

Invece di

public StudentMarks(double[] marks){ 
    this.marks = new double[0];  
} 

Questo vuole essere un sistemato versione del codice. Dai un'occhiata ai commenti in linea per maggiore chiarezza.

public class StudentMarks{ 

protected double[] marks; 
//create an array filled with double values 

//Pass in the array of marks to initialize the class 
public StudentMarks(double[] marks){ 
    this.marks = marks; //set the marks array in the class to the passed in one 
} 

//Set the class marks variable to the passed in one 
public void setMarks(double[] marks){ 
    this.marks = marks; 
} 

//Change the name to "printMarks" to better reflect the purpose of the method 
public void printMarks(){ 
    //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) { 
    //Print out an error and exit only if we have less than 1 element passed in 
    if (args.length != 7){ 
     System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5"); 
     System.exit(-1); 
    } 

    double[] prompt = new double[args.length]; 
    //Note that there is no error checking here 
    for (int i =0; i<args.length; i++){ 
     prompt[i] = Double.parseDouble(args[i]); 
    } 

    //Initialize the StudentMarks class with the value of the input 
    StudentMarks test = new StudentMarks(prompt); 

    test.printMarks(); 

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

} 
+0

"L'applicazione si interromperà ogni volta che viene passato più di un argomento." Nel momento in cui lo hai postato, OP aveva aggiornato la condizione a '! = 7'; OP sembra avere un requisito molto specifico su questo. –

+0

Grazie per il suggerimento @Andy Turner. Al momento in cui ho scritto il codice, l'OP ha ancora '! = 1', quindi ho fatto un'ipotesi e l'ho modificata. Tuttavia, hai ragione, sembra che abbiano un requisito specifico. Ho modificato il mio codice per abbinarlo. –

+0

"In realtà c'erano un paio di problemi con il codice sopra." È vero ora che hai rimosso la cosa riguardo a 'length <1'? Tenderei ad evitare di inviare grandi dump di codice perché non è molto chiaro cosa (e perché) hai cambiato semanticamente oltre a quel costruttore (devi scorrere su e giù per vedere le modifiche, non molto facile). Non dimenticare che le cose per te più chiare non sono necessariamente più chiare per gli altri che la leggono. –

Problemi correlati