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?

2
  • I think you're confusing the {} block. That block is not linked to armour in any way. Commented Nov 19, 2013 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. :) Commented Nov 19, 2013 at 14:10

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Yea, I extended my answer.
In the actual code, the armour info is in a class of it's own. This was just a little test class
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:

1 Comment

Oh thanks! It worked :D I hate it when a massive problem boils down to missing one word.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.