deftz
deftz

Reputation: 11

java.lang.NullPointerException with arrays

Hey the names in the program are in portuguese but I think its understandable, if you have any doubt just ask and i'll translate.

So I'm getting a NullPointerException with these. The array Vector_Canais is initialized in the constructor:

public Box(int capacidade) {
        Time a = new Time();
        Vector_Canais = new Canal[DEFAULT_SIZE];
    }

public static void novoCanal() {
        Scanner in = new Scanner(System.in);

        Cnl = in.nextLine();
        Vector_Canais[i] = new Canal(Cnl);      
        i++;
    }

    public static String listaCanais(int i) {
        return (Vector_Canais[i].getCanal());
    }

public static void listaCanais() {
        for (int a = 0; a < 100; a++) {
            if (Box.listaCanais(a) != null) {
                System.out.println(Box.listaCanais(a));
            }
        }

i is initialized at 0. Any ideas?

Upvotes: 0

Views: 107

Answers (2)

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

Most probably you haven't initialized the array Vector_Canais or you haven't initialized all of its members (for instance, novoCanal hasn't been called 100 times before). Remember, making an array of size 100 (of a class) means making an array of 100 null slots, not 100 objects. Until you call a constructor for each of them, they may throw this.

Upvotes: 3

Bohemian
Bohemian

Reputation: 424993

You haven't shown where Vector_Canais is initialized - my guess is you are not initializing it.

Try this:

static private Vector_Canais Canal[] = new Canal[100]; // for example

Upvotes: 1

Related Questions