Cannot invoke “ ” because array is null

Tags: , , ,



I need to add information about 2 actors such as their name, address and age and have done so without arrays easily but it’s necessary, I keep getting the error

“Cannot invoke “TestActor.setName(String)” because “actors[0]” is null at TestMain.main(TestMain.java:5)”

This is just a test main I’m using to test it ”’

public class TestMain {
public static void main(String[] args) {
    TestActor[] actor = new TestActor[2];
    //Actor act1 = new Actor(" ", " ", 0);
    actor[0]= ("");
    actor[0].setName("Jack Nicholson");
    actor[0].setAddress("Miami.");
    actor[0].setAge(74);
    actor[0].printAct();
}

And this is the actor class I’m using that I need to set the information from

public class TestActor {
    private String name;
    private String address;
    private int age;

    public TestActor(String s, String g, int p) {
        this.name = s;
        this.address = g;
        this.age = p;
    }

    public void setName(String s) {
        name = s;
    }

    public void setAddress(String g) {
        address = g;
    }

    public void printAct() {
        System.out.println("The actor's name is " + name + " and age is " + age + ". They live in " + address);
    }

    public void setAge(int p) {
        age = p;
    }

    public String toString() {
        return "The actor's name is " + name + " and age is " + age + ". They live in " + address;
    }

}

I know the toString doesn’t do anything there the way I have it setup just for the time being. It might be a bit of a mess and I might be in totally the wrong track. I was able to do it relatively easily wihtout using arrays but they’ve kinda stumped me and I’m not 100% sure on the direction to go in without maybe butchering the whole thing.

Answer

Compiler is complaining because you’re not initializing TestActor object correctly. You should rather do this:

actor[0] = new TestActor("Jack Nicholson", "Miami.", 74);
actor[0].printAct();

If you don’t want to do this and use setters manually, then you need to define a default constructor in TestActor:

public TestActor() {  }

then you should be able to use it in your arrays like this:

actor[0] = new TestActor();
actor[0].setName("Jack Nicholson");
actor[0].setAddress("Miami.");
actor[0].setAge(74);
actor[0].printAct();


Source: stackoverflow