I am writing a program that will enter an array of Students with their name and gpa’s and return only the failing students. I am unsure how to return an array that will avoid returning null as an element of that array. I.e. if there are 4 students in the initial array, but only 2 are failing, my array is returning: 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;
}
My current result when I do a test run in main is:
name = Jim gpa = 1.4
name = Bill gpa = 1.2
null
null
If the only problem is printing the nulls, i.e. it’s OK if your array has
nullvalues but you don’t want to see them in your output, then you can leave your method as it is and change your printing code so that it checks fornull, and avoid printing them.But if you must keep
nullvalues out of your array, you can use a dynamically resizing data structure likeArrayList, and get an array out of it using thetoArraymethod.Without using
ArrayList, since you’re tracking how manyStudentobjects represent failing students with thejvariable, after you collect the failing student objects you could create a new array of the desired length, and then fill it with only the non-null students using a loop, or usingArrays.copyOf, orSystem.arraycopy.