0

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?

  • I think you're confusing the `{}` block. That block is not linked to `armour` in any way. – m0skit0 Nov 19 '13 at 13:00
  • Yeah, I'm fairly new to Java (well, programming in general) and I only leaned about 2d arrays ~2 days ago, so yeah. :) – TheScottymo Nov 19 '13 at 14:10

2 Answers2

5

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
Adam Arold
  • 29,285
  • 22
  • 112
  • 207
1

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:

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147