Pztar
Pztar

Reputation: 4749

Java - Why am I getting this NullPointerException?

I don't understand why this is giving me a null pointer exception when I try to add a value to the a1[i] array.

public class Array {

String text;
int total = 0, count = 0;

Array[] a1 = new Array[100];
Scanner scan = new Scanner(System.in);



public void setData() {
    int i=0;

    System.out.println(a1.length);
    do {

        System.out.println("Enter some data: ");
        text = scan.next();
        if (text.equals("end"))break;
        a1[i].text = text; //I get a null pointer exception here. Not sure why. 
        i++;

    } while (true);

    }

Upvotes: 1

Views: 1736

Answers (4)

firen
firen

Reputation: 1424

Array[] a1 = new Array[100]; //here you just create an array of references to objects which are set to null
a1[i].text = text; //before this line you should assign to a1[i] a reference to Array object for example a1[i] = new Array();

Upvotes: 0

devsnd
devsnd

Reputation: 7722

You are getting a null-pointer exception, because you have allocated the space for 100 array elements, but you still need to initialize them:

So before accessing a1[i].text you need to initialize it by calling a1[i] = new Array()

Also I am quite sure, that you actually wanted to create some other kind of object, not Array. Array the class you are currently writing, as I understand, so you probably want to have multiple Strings, e.g. String[].

I recommend to you to use a LinkedList instead.

Upvotes: 0

JRaymond
JRaymond

Reputation: 11782

Because there isn't an object stored at a1[i]. What you're essentially saying at that line is:

null.text = text

which will break every time

Upvotes: 0

Makoto
Makoto

Reputation: 106389

Everything initialized in the a1 array is null. You'd have to put a new instance of Array() in there before doing anything with the member methods.

What this translates to: Every time you want to do something with a1[i], you'd have to have a new instance of Array in there first.

Example:

for(int i = 0; i < n; i++) {
    a1[i] = new Array();
}

Upvotes: 2

Related Questions