-1

Instead of me having to create a new case for each colour I decide to add, is there an alternative to using a switch statement with strings from an array as the cases? Here is my code!

public static String[][] colours = { { "red", "933" },
        { "lblue", "359770" }, { "blue", "428770" },
        { "orange", "461770" }, { "pink", "123770" } };

public static void changeColour(String col, Player player) { // changeColour("red", player);
    switch (col) {
    case "red":
        player.setColour(Integer.parseInt(colours[0][1]));
        break;
    case "lblue":
        player.setColour(Integer.parseInt(colours[1][1]));
        break;
    case "blue":
        player.setColour(Integer.parseInt(colours[2][1]));
        break;
    case "orange":
        player.setColour(Integer.parseInt(colours[3][1]));
        break;
    case "pink":
        player.setColour(Integer.parseInt(colours[4][1]));
        break;
    }
}
Daenyth
  • 35,856
  • 13
  • 85
  • 124
Arpp
  • 5
  • 2

4 Answers4

6

Instead of the case why not use a Map instead this way you would just add to the Map and not worry about continuing the case statements for every piece

Map<String, Integer> colorMap = new HashMap<String, Integer>() {{
   put("red", 999);
   put("green", 639);
}};

Then you can just use colorMap.get("red") and it will return you the correct Integer

darren102
  • 2,830
  • 1
  • 22
  • 24
2

another solution is using enum

enum Colour {
   red(933), blue(428770), // etc.
   ;

   int code;
   Colour(int code) {this.code = code;}
   int getCode() {return code;}
}

and rewrite your method as

void changeColour(Colour colour, Player player) {
   player.setColour(colour.getCode());
}
karakfa
  • 66,216
  • 7
  • 41
  • 56
1

What you are looking for is a HashMap

Map<String, Integer> map = new HashMap<String, Integer>();

There is no way to use switch without explicitly setting all the cases.

Silvery
  • 1,358
  • 2
  • 8
  • 8
0

I assume you want something like this

public static void changeColour(String col, Player player) 
{
    for(int i=0; i<colours.length; i++)
    {
        if(col.equals(colours[i][0]))
            player.setColour(Interger.parseInt(colours[i][1]);
    }
}