简体   繁体   中英

Can someone please tell me what is wrong with the for loop

So I'm supposed to make a deck of cards and I'm doing it in this way. No CT error but I get IndexOutOfBound Exception. I dont know why. The class Card is already defined. The value goes up to 12 and the suit goes up to 3, inclusive. Thank you!

ArrayList<Card> deck = new ArrayList<Card> (52);

public StandardDeck()
{
   buildDeck();
}

public void buildDeck()
{
   int index = 0;
   for(int suit = 0; suit <= 3; suit++)
   {
      for(int value = 0; value <= 12; value++)
      {
         deck.set(index, new Card(value, suit)); 
         index++;
      }   
   }

}//buildDeck

Don't use

deck.set(index, new Card(value, suit)); 

Use

deck.add(new Card(value, suit)); 

set() throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size()) . Therefore, before you add the i'th element, you can't call set(i-1,...) , which is exactly what you tried to do.

You should do like this:

for(int suit = 0; suit <= 3; suit++)
{
   for(int value = 0; value <= 12; value++)
   {
      deck.add(new Card(value, suit)); 
      index++;
   }   
}

The arraylist doesn't have anything in it yet you need to add first then you can use set for valid indexes. Once you have the full deck then you can do deck.set(index, card); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM