程序打印空值

时间:2015-04-27 01:58:50

标签: java null pojo

我正在尝试使用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);
   }
 }

名称打印清晰,以及等级,但测试中的值不打印。

1 个答案:

答案 0 :(得分:3)

您分配给testScores的唯一内容是testScores

this.testScores = testScores;

为空。它只在默认构造函数中初始化,永远不会被调用。

除非您需要将testScores作为数组供以后使用,否则为什么不在courseGrade

中迭代时创建包含值的字符串

e.g

// field
StringBuilder testScores  = new StringBuilder ();

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