I have a class named Card and I have this for loop:
int i;
for (i = 0; i < 13; i++) {
Card cardNameHere = new Card();
}
What I want to do is create new instances based on the for loop. So for example, I would like the names to be card1, card2, card3, etc. The number would come from the for loop.
I have tried this and it does not seem to work:
int i;
for (i = 0; i < 13; i++) {
Card card[i] = new Card();
}
Can anyone tell me what I am doing wrong?
Thanks.
So I am using the solution from Hovercraft Full Of Eels, but I have another problem.
I am using cardList.add(new Card()); , and when I try to use Card(i) to set the name, java won't let me do it. Using it without i works fine, but how do I access it so I can call another method on it such as setId. I would like to call cardName.setId();
Create your array before the loop, and fill it inside the loop. Better to use an ArrayList though.
List<Card> cardList = new ArrayList<Card>();
for (i = 0; i < MAX_CARD; i++) {
cardList.add(new Card());
// or new Card(i) as the case may be
}
If you're filling a deck of cards, and you have your Suit and Rank enums nicely created, then:
List<Card> cardList = new ArrayList<Card>();
for (Suit suit: Suit.values()) {
for (Rank rank: Rank.values()) {
cardList.add(new Card(suit, rank));
}
}
Edit
You state in comment:
So I am using cardList.add(new Card()); , and when I try to use Card(i) to set the name, java won't let me do it. Using it without i works fine, but how do I access it so I can call another method on it such as setId. I would like to call the cardName.setId();
Card(i)
doesn't make sense as you can't treat the Card class as if it were a method -- again I'm not even sure what to make of it, what you're trying to do here. If you need to extract a Card from the ArrayList, you will need to call the get(...)
method on the ArrayList, here called cardList
. Better still would be to set the Card properties in its constructor as I show in my 2nd code snippet.
In Java, variable names have to be known at compile-time. Even in other languages like JavaScript, where that is not true, it is a good idea to not try to dynamically create variables at runtime.
This is exactly what arrays are meant to solve: when you have items of a known type, but unknown quanity at compile time. You need to declare the card as an array: Card[] cards
Card[] cards = new Card[13];
for (int i = 0; i < cards.length; i++) {
cards[i] = new Card();
}
Notice I changed the for loop to loop through to cards.length, which is figured out at runtime, so that 13 does not have to be hard-coded in both places.