missing array, making a deck of cards

So I kept getting this error:
Will also post the Deck Class below:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
 at java.util.ArrayList.rangeCheck(Unknown Source)
 at java.util.ArrayList.remove(Unknown Source)
 at nellie.tobey.crazyeights.Deck.deal(Deck.java:39)
 at nellie.tobey.crazyeights.CrazyEights.deal(CrazyEights.java:53)
 at nellie.tobey.crazyeights.CrazyEights.<init>(CrazyEights.java:24)
 at nellie.tobey.crazyeights.CrazyEights.main(CrazyEights.java:94)



It took me a stupid long time of printing of the results of all the different methods before I found the problem.

When the deck is created, it's named cards.  When I shuffled it, all the items in the array are removed and put into a new array named shuffled.  That left my cards array empty.  I forgot to change the name of shuffled(Array) back to cards(Array) when the task was complete.

I don't know if any one else will find this useful, but I know I had a hard time finding out what was going on.  (All-be-it such a simple error).



The DECK class:  Making a deck of cards




package nellie.tobey.crazyeights;
import java.util.ArrayList;
import java.util.Random;
import nellie.tobey.cards.Card;

public class Deck {
 private ArrayList<Card> cards = new ArrayList<Card>();
 private Random rand = new Random();

 public Deck() {
  for(int i=0; i <52; i++) {
   Card card = new Card(i);
   cards.add(card);
 //checking the ArrayList for the deck of cards --->
  //System.out.println(cards.get(i));
  }
  shuffle();
 
 }

 public void shuffle() {
  ArrayList<Card> shuffled = new ArrayList<Card>();
  int numberOfTimes = cards.size();
  for(int i=0; i<numberOfTimes; i++) {
   int deckSize = cards.size();
   int pick = rand.nextInt(deckSize);
   Card card = cards.remove(pick);
   shuffled.add(card);
   //checking the ArrayList for the deck of cards shuffled --->
   //System.out.println(shuffled.get(i));
  }
  cards = shuffled;
 }

 public Card deal() {
 
  Card card = cards.remove(0);
 
  return card;
  
  }

 public void reuse(ArrayList<Card> newCards) {
  cards = newCards;
 }
 public int size() {
  return cards.size();
 }
 public String toString() {
 
  String deckString = "";
  for(int i = 0; i<cards.size(); i++) {
   Card card = cards.get(i);
   deckString += card + " ";
  
  }
  return deckString;
 }

}

Comments

Popular posts from this blog

Statistics, Python, Making a Stem Plot

Pandas Python and a little probability

JavaScript Ascii animation with while loops and console.log