我正在编写一个程序,该程序将使用他们的姓名和 gpa 输入一组学生,并只返回失败的学生。我不确定如何返回一个避免null
作为该数组元素返回的数组。即,如果初始数组中有 4 个学生,但只有 2 个学生失败,则我的数组返回:student1, student2, null, null。
Student Jim = new Student("Jim",1.4);
Student Tom = new Student("Tom",3.0);
Student John = new Student("John",4.0);
Student Bill = new Student("Bill",1.2);
Student[] group1 = {Jim,Tom,John,Bill};
public Student[] getFailing(Student[] students) {
int i, j;
Student[] failing = new Student[students.length];
Student temp;
for(i=0, j=0; i< students.length; i++){
if(students[i].getGpa() < 2.0){
temp = students[i];
failing[j] = temp;
j++;
}
}
return failing;
}
我在 main 中进行测试运行时的当前结果是:
name = Jim gpa = 1.4
name = Bill gpa = 1.2
null
null