How would I create a new object from a class using a for loop in java?

前端 未结 2 385
醉梦人生
醉梦人生 2021-01-15 15:05

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

相关标签:
2条回答
  • 2021-01-15 15:47

    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.

    0 讨论(0)
  • 2021-01-15 15:57

    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.

    0 讨论(0)
提交回复
热议问题