I want to figure out why my array that is declared outside of a for loop
refuses to be properly initialized by a for loop
in order to be used by another for loop
. Googling "array null pointer exception" and "null arrays" kept bringing me to errors about not initializing the array. Hopefully that's not what's happening here. (I don't think it is.)
public static void main(String[] args)
{
Student[] students = new Student[25];
for(Student student : students)
{
int grade=(int)(Math.random()*4 +1);
student = new Student("bob",grade);
System.out.println(student); //debug 1
}
for(Student student : students)
{
// if (student.getGPA() == 0){
// System.out.println("No data entered for student.");
// }
System.out.println(student); //debug 2
}
}
This block is just main, and it's in another valid class named after the file. Student is a class that I excluded because it has nothing to do with the question being asked, but for reference it takes a String name and an int gradeLevel as parameters and has toString() and getGPA() methods (among others).
What I want from debug 2 and get from debug 1: something along the lines of
bob: Freshman; GPA: 0.00
bob: Senior; GPA: 0.00
bob: Freshman; GPA: 0.00
bob: Sophomore; GPA: 0.00
bob: Senior; GPA: 0.00
What I have from debug 2:
null
null
null
null
null
I want the print statement marked "debug 2" to print the same thing as what "debug 1" does, which is a column of the toString values of the students. Instead, I'm just getting a column of null for debug 2 but the correct output for debug 1.
The commented-out code was the source of null pointer exceptions because null objects do not have getGPA() methods. I have no idea why the array remains full of nulls, though. The fact that there aren't nulls from debug 1 tells me that the array is indeed being initialized, but that the values aren't staying in the array.
I probably completely misunderstand something or the use of something here.