我正在寫一個程序,它將輸入一組學生的名字和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;
}
我現在的結果是,當我做了測試運行中主要是:
name = Jim gpa = 1.4
name = Bill gpa = 1.2
null
null
'System.arraycopy'很好,但是瞭解['Arrays.copyOf']是有用的(http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html# copyOf%28T [],%20int%29)。後者稱之爲前者,但我發現它使用起來稍微容易一些。 –
@MichaelMcGowan謝謝,不錯的提示。我總是忘記'Arrays.copyOf' – pb2q
@MichaelMcGowan,有沒有辦法在拷貝我的數組之前找到null的索引,所以我知道我的新數組的長度?或者是內置到Arrays.copyOf? – gotguts