2

I have created three initializer arrays that must be used in the 'students' array, which should be an array of student objects. Every time it runs, a NullPointer error appears.

class School
{
   private Student[] students;
   private int size;

   public School (int s)
   {size = s;}

   public void addData()
   {
      String[] name = {"Tom", "Ann", "Bob", "Jan", "Joe", "Sue", "Jay", "Meg", "Art", "Deb"};
      int[] age = {21, 34, 18, 45, 27, 19, 30, 38, 40, 35};
      double[] gpa = {1.685, 3.875, 2.5, 4.0, 2.975, 3.225, 3.65, 2.0, 3.999, 2.125};

      for(int i = 0; i < size; i++){
          students[i] = new Student(name[i], age[i], gpa[i]);
        }
   }  

   public String toString()
   {
       String s = "";
       for(int i = 0; i < size; i++){
           s = s + students[i].toString();
        }
        return s;
   }
}

 class Student
{
   private String name;
   private int age;
   private double gpa;

   public Student (String n, int a, double g)
   {
      name = n;
      age = a;
      gpa = g;
   }

   public String getName() { return name; }  
   public int getAge()     { return age; }  
   public double getGPA()  { return gpa; }

   public String toString()
   {
      String temp = name + "  " + age + "  " + gpa + "\n";
      return temp;
   }
}

Where does the problem exactly begin and how would it be resolved?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Array `students` is never initialized. `students = new Student[10];` in the constructor, but you'll also have problems if the size passed in is anything other than 10. – David Conrad Jan 17 '20 at 03:21

3 Answers3

1

Initialize like this:

private Student[] students = new Student[100]

Ideally, student array must be larger than size, but size is defined after student array, so we cannot do that and must use a random big enough array length.

Jol
  • 23
  • 6
0

The Student array is not initialized. In java , you need to declare the array and initialize it too with a size. Example :

private Student[] students = new Student[5];
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
parthi
  • 101
  • 8
0

here you have not initialized size of array, so at runtime students array is referring to null.

By this line you are trying to allocate in memory which you have not initialized yet.

students[i] = new Student(name[i], age[i], gpa[i]);

So first do below change

private Student[] students = new Student[7];
Shardendu
  • 3,480
  • 5
  • 20
  • 28