TheScottymo
TheScottymo

Reputation: 54

2d array in Java returns null result

I'm trying to make an armour system for a text game using a 2D array in Java. I've got it all figured out in my head but the code doesn't seem to work.

public static String[][] armour = new String[2][3];
{
    armour[0][0] = "shirt";
    armour[0][1] = "plate";
    armour[0][2] = "iron";
    armour[1][0] = "1";
    armour[1][1] = "0.75";
    armour[1][2] = "0.5";
}
public static void main(String[] args) {
    System.out.println(armour[0][1]);
}

This should return "plate" but it doesn't, and I have been looking it up, modifying it and all sorts for hours now and I cannot for the life of me figure it out. Does anybody here know?

Upvotes: 0

Views: 534

Answers (2)

Adam Arold
Adam Arold

Reputation: 30538

You are using an instance initializer block where you should have been using a static one.

public static String[][] armour = new String[2][3];
static {
    armour[0][0] = "shirt";
    armour[0][1] = "plate";
    armour[0][2] = "iron";
    armour[1][0] = "1";
    armour[1][1] = "0.75";
    armour[1][2] = "0.5";
}

Try this it will do the trick. You are not making an instance of your class and any block without the static keyword will only run if an instance is created.

Another option is using the array initializer block:

public static String[][] armour =
        {{"shirt", "plate", "iron"},{"1", "0.75", "0.5"}};

I have some remarks though:

  • public static variables are asking for trouble. use private variables or constants (public static final)
  • You should move the armour information to their separate class OR use a Map to store the key-value pairs: shirt -> 1

Upvotes: 5

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Create a static initializer:

static {
    armour[0][0] = "shirt";
    armour[0][1] = "plate";
    armour[0][2] = "iron";
    armour[1][0] = "1";
    armour[1][1] = "0.75";
    armour[1][2] = "0.5";
}

Otherwise, you will have to have a class instance in order to get the code block executed.

More info:

Upvotes: 1

Related Questions