程序打印空值



我正在尝试使用 toString() 打印数组,但是当我需要数字时,Null值会打印。我一定是在我的程序中造成了内存泄漏。请帮忙

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; //average
    }
    if (average >= 90)     //determines 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; 

    }
}

还有我的测试员类:

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

名称和等级打印清晰,但测试上的值不会打印。

你唯一分配给testScores的就是testScores

this.testScores = testScores;

这是空的。 它仅在从不调用的默认构造函数中初始化。

除非您需要将testScores作为数组供以后使用,否则为什么不创建一个包含值的字符串,因为您可以在courseGrade中迭代这些值

例如

// field
StringBuilder testScores  = new StringBuilder ();
// `courseGrade`
for ( int x = 0; x < list.length; x++)
{
     testScores.append (list[x]).append (",");
     ....

最新更新