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

前端 未结 2 403
醉梦人生
醉梦人生 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:57

    Create your array before the loop, and fill it inside the loop. Better to use an ArrayList though.

    List cardList = new ArrayList();
    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 cardList = new ArrayList();
    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.

提交回复
热议问题