How to use a table of another type of class?

advertisements

I have declared a class named Member. I then assigned an array with Member type. When I try to put things into the array, it gives me this error:

Exception in thread "main" java.lang.NullPointerException
    at HW2_2.main(HW2_2.java:15)

This is my code:

import c.Member;

import java.util.Scanner;
public class HW2_2
{
     public static void main(String []args)
     {
         Member[] p = new Member[100];
         Scanner in = new Scanner(System.in);
         p[0].setID("apple12");
         p[0].setPassword("1234");
         p[0].setFirstname("fname");
         p[0].setLastname("lname");
         p[0].setEmail("*@gmail.com");
     }
 }

How do I fix this to the point where I can store data into my array?


You have created an object p which points to an array of Member objects. This is perfect. However, each object in your array is by default null. You cannot simply perform operations on them.

You probably want to do something like...

//...
p[0] = new Member(...);
p[0].setId("ID");
//... And so on

What's important to learn from here is that an array declaration syntax does not initialize the values of the array itself. That would be impossible, right? How would you pass arguments to the constructors of each one seperately? You have to do it manually.