【发布时间】:2012-09-25 23:45:53
【问题描述】:
我正在编写一个程序,该程序将输入一组包含学生姓名和 gpa 的学生,并只返回不及格的学生。我不确定如何返回一个数组,以避免将null 作为该数组的元素返回。 IE。如果初始数组中有 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
【问题讨论】: