-2

Say I have the class:

package school;
public class SchClass {
    private Student[] students;
    private int numStudents = 0;
    public SchClass() { 
    }
    public void addStudent(Student s) {
        this.students[this.numStudents] = s;
        this.amountStudents++;
    }
}

and I am trying to run this in another class:

import school.SchClass;
import school.Student;
import school.Tutor;
public class JavaTesting {
    public static void main(String[] args) {
        Student s = new Student();
        Tutor t = new Tutor();
        SchClass shc = new SchClass();
        sch.setTutor(t);
        sch.addStudent(s);
    }
}   

When I do this, it reports this NullPointerException:

Exception in thread "main" java.lang.NullPointerException
    at school.SchClass.addStudent(SchClass.java:8)
    at javatesting.JavaTesting.main(JavaTesting.java:10)

What is wrong? I'm sure I coded this perfect but it still reports an error.

Okx
  • 353
  • 3
  • 23

2 Answers2

2

member students is null

  public class SchClass {
        private Student[] students = new Student[ size ];
        private int numStudents = 0;
        public SchClass() { 
        }
        public void addStudent(Student s) {
            this.students[this.numStudents] = s;
            this.amountStudents++;
        }
    }

and it will work only untils amountStudents < size, then execption will occur so better is

public class SchClass {
    private List< Student > students = new ArrayList< Student >();
    public SchClass() { 
    }
    public void addStudent(Student s) {
        this.students.add( s );
    }
}
Robert Wadowski
  • 1,407
  • 1
  • 11
  • 14
0

Read about the Collection framework. If you want dynamic "arrays" you may use List<T>

Arrays are not dynamic.

Also, you have numerous errors in your class. What is for example this.amountStudents++ supposed to do? Furthermore I am surprised that your code does not already fail at sch.setTutor(t);, since you do not have declared a variable called sch. Did you mean shc?

luksch
  • 11,497
  • 6
  • 38
  • 53