0

Does this way of adding a string to an Array List work? When a player is level 2+ , a new enemy should be added to the Array List. I am only showing the code that is important to the question but basically a random enemy is chosen from the Array List for the player to face.

int level = player.level;

ArrayList<String> enemies2 = new ArrayList<String>(); {

    if (level >= 2) {
    enemies2.add("Giant");
    }

    enemies2.add("Skeleton");
    enemies2.add("Zombie");
    enemies2.add("Warrior");
    enemies2.add("Assassin");
    enemies2.add("Reaper");
    enemies2.add("Archer");
}
  • Despite being confusing code to read: the `{..}` here is an [*anonymous code block*](http://stackoverflow.com/questions/1563030/anonymous-code-blocks-in-java) and the braces are unnecessary; it should not be confused with any sort of initializer. Why "doesn't it work"? Make sure the question is clear - and try out things; as the compiler (and actual execution of the program) will provide useful feedback. – user2864740 Jan 08 '17 at 00:31
  • Okay thank you, my eclipse compiler tells me to put curly brackets after the ArrayList and at the end. –  Jan 08 '17 at 00:34
  • Hmm. Arbitrary "style" setting I suppose, *sigh*. – user2864740 Jan 08 '17 at 00:35
  • I think that your compiler is saying to you use something like: new ArrayList() {{ add("Giant"); add("Skeleton"); }}; – Felipe Nathan Campigoto Jan 08 '17 at 00:37
  • Your if statement needs to be within a method as does your enemies2.add() methods. Perhaps within a initialize() method or what the heck...even main() method. – DevilsHnd - 退職した Jan 08 '17 at 00:52

1 Answers1

0

I would recommend

int level = player.level;

ArrayList<String> enemies2 = new ArrayList<String>();
enemies2.add("Skeleton");
enemies2.add("Zombie");
enemies2.add("Warrior");
enemies2.add("Assassin");
enemies2.add("Reaper");
enemies2.add("Archer");
if(level >= 2) { enemies2.add("Giant"); } // if you want it on one line

For double brace initialization you don't need the enemies2 before the add()

ArrayList<String> enemies2 = new ArrayList<String>() {{
    add("Skeleton");
    add("Zombie");
    add("Warrior");
    add("Assassin");
    add("Reaper");
    add("Archer");
}};
  • Thank you but I am starting to realize that my issue is the fact that the "level" is what is breaking the program. I am getting that value from another class and it does not like that. When I removed the initialization of the other class which was Player player = new Player(); and got rid of the level variable, it worked. –  Jan 08 '17 at 00:49