jeudi 29 mars 2018

java.lang.ArrayIndexOutOfBoundsException: 0 When using ArrayList

For some reason this exception is being thrown when I try to run this code and I have no idea how to fix it. I understand that it is to do with the contents of the list however I have declared them outside this method and it but the exception continues to be thrown.

public class Deck {
private int i;
Random rand = new Random();
public String[] playerHand = {};
private String[] computerHand = {};
public String[] deck = {"CA", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "CJ", "CQ", "CK", "DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10", "DJ", "DQ", "DK", "HA", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "H10", "HJ", "HQ", "HK", "SA", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10", "SJ", "SQ", "SK2"};
private  ArrayList<String> deckList = new ArrayList<String(Arrays.asList(deck));
private String[] pile = {};
ArrayList<String> pileList = new ArrayList<String>(Arrays.asList(pile));

public void startGame(){
   for(i = 0; i < 5; i++){
       playerHand[i] = deckList.get(rand.nextInt(deckList.size()));

       deckList.remove(playerHand[i]);
   }
    for(i = 0; i < 5; i++){
       computerHand[i] = deckList.get(rand.nextInt(deckList.size()));
       deckList.remove(computerHand[i]);
    }
    pile[0] = deckList.get(rand.nextInt(deckList.size()));
    deckList.remove(pile[0]);

}

The exception thrown is "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at card.game.Deck.startGame(Deck.java:28)"

Not sure but the random function may have something to do with it.




Aucun commentaire:

Enregistrer un commentaire