问题描述:

I am trying to print an array using toString() but there are Null values that print when I'm expecting numbers. I must have caused a memory leak in my program. Please help

public class StudentData

{

// instance variables

private String firstName,lastName;

private double[] testScores; //array

private char grade;

public StudentData()

{

firstName = "";

lastName = "";

testScores = new double[5];

grade = '*';

}

/**

* Constructor for objects of class StudentData

*/

public StudentData(String fName,String lName,double ... list)

{

// initialise instance variables

firstName = fName;

lastName = lName;

testScores = list;

grade = courseGrade(list); //calc

}

public char courseGrade(double ... list) //returns a char (grade)

{

double total = 0,sum = 0,average = 0;

for ( int x = 0; x < list.length; x++)

{

total += list[x]; //sum

average = total/list.length; //avaerage

}

if (average >= 90) //determine the grade

return 'A';

else if (average >= 80)

return 'B';

else if (average > 70)

return 'C';

else if (average > 60)

return 'D';

else

return 'F';

}

public String toString ()

{

return firstName + "\t" + lastName + "\t" + testScores + "\t" + grade;

}

}

And my tester class:

public class TestProgStudentData

{

public static void main (String [] args)

{

StudentData student1 = new StudentData("John", "Doe",89, 78, 95, 63, 94);

StudentData student2 = new StudentData("Lindsay", "Green", 92, 82, 90, 70, 87, 99);

System.out.println(student1);

System.out.println(student2);

}

}

The names print clearly, as well as the grade, but the values on the test do not print.

网友答案:

The only thing that you ever assigning to testScores is testScores

this.testScores = testScores;

which is null. it is only intialized in the default constructor which is never called.

Unless you need the tesScores as an array for later use, why not create a string containing the values as you iterate over them in courseGrade

e.g

// field
StringBuilder testScores  = new StringBuilder ();

// `courseGrade`
for ( int x = 0; x < list.length; x++)
{
     testScores.append (list[x]).append (",");
     ....
相关阅读:
Top