0

I am new at java and i have this exception in my code:

Exception in thread "main" java.lang.NullPointerException
    at Course.addStudents(Course.java:31)
    at Third.main(Third.java:28)

Course.java

public boolean addStudents(Student newStudent){
     for (Student student : students){
         if (student.getID()== newStudent.getID()){
             return false;
         }
     }
     if(numberOfStudents < capacity){    
         students[numberOfStudents++] = newStudent;
         return true;
     }
     return false;
     }

Third.java

c1.addStudents(s1);

I have tried the solve it but didnt achieve. I searched for it and I guess the problem is initializing. Is it true? if it is, I dont know how to handle with that, any idea??

13
  • 1
    Is students initialized? Are all its elements initialized? Commented Jan 8, 2014 at 19:20
  • 1
    What line is line 31 in Course.java? Commented Jan 8, 2014 at 19:20
  • no it isnt but i dont know how to initialize it? Commented Jan 8, 2014 at 19:21
  • 2
    @DavidBo and user2065083 : read the code. students is an array, not a List. Commented Jan 8, 2014 at 19:26
  • 1
    @user3075117 In the place where you declared the array. Or show us Course.java code. Commented Jan 8, 2014 at 19:33

2 Answers 2

3

As per your comment

  for (Student student : students){

students is an array and not initialized.

Since you are using arrays , that initialization would be

Student[] students = new Student[capacity];

Remmeber that when you intialize an array ,default values will be null untill unless you fill them. In your loop you have to check for null as again it causes NullPOinterException

 for (Student student : students){   
         if (student !=null && student.getID()== newStudent.getID()){
             return false;
         }
     }
Sign up to request clarification or add additional context in comments.

2 Comments

No look the later codes students[numberOfStudents++] = newStudent; OP is trying to use an array I guess.
While true, he's also going to need a check for null inside his loop, since the elements of the array aren't initialized.
2

the problem, is indeed initializing, one or more of the below is not initialized:

newStudent, students.

as Student is an object it needs an initialization before you can use it, as opposed to primitive types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.