ShacoNotFound404
ShacoNotFound404

Reputation: 21

Why do i get NullPointerException in my input?

i'm a beginner java programmer and i did some research but i cannot understand how to apply it to my program.

when i run my program, i get a NullPointerException as i enter the nickname for the first IP Address. Why?

the isolated line in the code is where i get the Exception.

Upvotes: 1

Views: 95

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234857

When you allocate an array like this:

IPAddress[] ipAddress = new IPAddress[2];

it creates an array with two slots, but both of the slots have null. You need to put something in each slot before you can use it as an object:

ipAddress[i] = new IPAddress();
ipAddress[i].nickname = input.next();

Inside local_address you are going to get another NPE. You set result to null initially and don't assign an array to it. That's why you're getting a NPE. You can fix this with:

String[][] result = new String[addr.length][]; // instead of null

However, you will also need to assign a String[] for each value of j. If you don't know what count will grow to be, you might consider using a List<String> that can grow automatically for you.

As an aside: I don't know what you're trying to accomplish, but your logic doesn't look correct. Do you really need a two-dimensional String array? It seems like this should be what you want:

static List<String> local_address(IPAddress addr[]) {
    List<String> result = new LinkedList<>();
    for (int j = 0; j < addr.length; j++) {
        IPAddress test = addr[j];
        if (test.xx == addr[j + 1].xx & test.yy == addr[j + 1].yy) {
            result.add(addr[j + 1].nickname;
        }
    }
    return result;
}

Upvotes: 2

gkrls
gkrls

Reputation: 2664

You have created an array of Ip Adresses but you never filled in any IP adress.

Here ipAddress[i].nickname = input.next(); you assume that ipAddress[i] holds an IPAdress object and try to set its nickname field to input.next(). But since you haven't added any objects to it, the array, is filled with the default value which is null.

Upvotes: 3

You are missing this line (before NullPointerException is thrown):

ipAddress[i] = new IPAddress();

You should initialize array's elements before.

Upvotes: 5

Related Questions