If your range of actions is very limited (say, 2 or 3 actions involving money, move squares, etc) then I might use the following class:
class Card {
// It would be a good practice to not make the following fields
// public and use getters/setters instead but I've made them this
// way just for illustration purposes
public String text;
public String action;
public int value;
Card(String text, String action, int value) {
this.text = text;
this.action = action;
this.value = value;
}
}
This way (as already pointed out by some other answers), you can use an array of Card
s instead of array of String
s. You can then have text in one field, the action in a separate field, and the value associated with that action in a third field. For example, you could have the following cards:
Card lose25 = new Card("You lose $25", "money", -25);
Card move5squares = new Card("Move 5 squares ahead!", "move", 5);
When you're 'processing' the cards, you can do so in the following manner:
...
if (card.action.equals("money") {
// Update user's money with card.value
} else if (card.action.equals("move") {
// Update user's position with card.value
} else if (card.action.equals("...") {
// and so on...
}
...
EDIT:
If the cards can hold more than one action, you can use a HashMap to store actions for that card:
class Card {
public String text;
public HashMap<String, Integer> actions;
Card(String text) {
this.text = text;
actions = new HashMap<String, Integer>();
}
addAction(String action, int value) {
actions.put(action, value);
}
}
A HashMap
is a collection that can store key-value pairs. So for a card that has 2 actions, you can use the above code as:
Card aCard = new Card("Lose $25 and move back 3 spaces!");
aCard.addAction("money", -25);
aCard.addAction("move", -3);
Now, when you're actually processing the cards, you need to check the HashMap
for all actions stored in this card. One way to iterate through the HashMap
is to do the following:
Card processCard = ...;
for (Map.Entry<String, Integer> entry : processCard.actions.entrySet()) {
// This loop will get each 'action' and 'value' that you added to
// the HashSet for this card and process it.
String action = entry.getKey();
int value = entry.getValue();
// Add the earlier 'card processing' code here...
if (action.equals("money") {
// Update user's money with value
} else if (action.equals("move") {
// Update user's position with value
} else if (action.equals("...") {
// and so on...
}
}