Reputation: 455
I am trying to create a deck of cards thus create 52 instances of a class which allows me to specify the card number and suit. For example, Card(2, "Clubs") would instantiate a card with the value 2 and the suit Clubs.
I am using the following code to loop the process and store in an array instead of typing it out 52 times. It works but trying to see if I could do it better. It looks rather bad with so many if/else coding. Tried to store the suits in an enum but I am unable to call it. It doesn't seem to match a String.
Also, this method means I would end up with even more if/else when I come to the picture cards Jack, Queen, King, Ace. Please advice if there is a better approach. Thanks.
Card[] cards = new Card[52];
int i = 0;
for(int x=0; x < 4; x++){
for(int y=2; y < 15; y++){
if(x == 0){
cards[i] = new Card(y, "CLUBS");
}
else if(x == 1){
cards[i] = new Card(y, "DIAMONDS");
}
else if(x == 2){
cards[i] = new Card(y, "HEARTS");
}
else{
cards[i] = new Card(y, "SPADES");
}
i++;
}
}
Upvotes: 0
Views: 59
Reputation: 2535
Slow way :)
for (String cardType: "CLUBS DIAMONDS HEARTS SPADES".split(" ")) {
for (int i = 2; i < 15; i++) {
cards[i] = new Card(i, cardType);
}
}
Upvotes: 0
Reputation: 16235
In order not to use more than one loop you could do the following
Card[] cards = new Card[52];
String type = "";
for(int i=0; i<52; i++) {
if (i<13) type = "CLUBS";
else if (i<26) type = "DIAMONDS";
else if (i<39) type = "HEARTS";
else type = "SPADES";
cards[i] = new Card(i%13, type);
}
Upvotes: 0
Reputation: 13907
Use a List
for the suits:
List<String> suits = new ArrayList<String>();
suits.add("CLUBS");
suits.add("DIAMONDS");
suits.add("HEARTS");
suits.add("SPADES");
Card[] cards = new Card[52];
int i = 0;
for (String suit : suits) {
for (int y = 2; y < 15; y++) {
cards[i] = new Card(y, suit);
i++;
}
}
You could also consider defining the suits in an enum:
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES;
}
In this case your loop would change to:
for (Suit suit : Suit.values()) {
for (int y = 2; y < 15; y++) {
cards[i] = new Card(y, suit.name());
i++;
}
}
Upvotes: 3
Reputation: 201537
You could always set the suit with something like this then,
for(int x=0; x < 4; x++) {
// Perhaps getSuit(x)?
String suit = "CLUBS";
if (x == 1) suit = "DIAMONDS";
else if (x == 2) suit = "HEARTS";
else if (x == 3) suit = "SPADES";
//--------------------
for(int y=2; y < 15; y++) {
cards[i] = new Card(y, suit);
i++;
}
}
You might also move the suit to an enum
.
Upvotes: 0
Reputation: 18173
Try using a java.util.Map<Integer, String>
which maps type indices to type Strings.
final Map<Integer, String> types = new HashMap<Integer, String>();
types.put(0, "CLUBS");
types.put(1, "DIAMONDS");
// ...
int i = 0;
for(int x=0; x < 4; x++){
for(int y=2; y < 15; y++){
cards[i] = new Card(y, types.get(x));
i++;
}
}
Upvotes: 1