Search code examples
javaarraysblackjack

I don't understand why it says ArrayOutOfBound error


I am trying to create a blackjack game.

First of all, I created an array called deck size 52 using a class constructor.

    public Deck(){
    for(int i=0; i<13; i++){ //Spades
      if(i>9){
        deck[i]=10;
      }
      else{
        deck[i]=(i+1);
      }
    }
    for(int i=13; i<26; i++){ //Hearts
      if(i>21){
        deck[i]=10;
      }
      else{
        deck[i]=(i-12);
      }
    }
    for(int i=26; i<39; i++){ //Clubs
      if(i>34){
        deck[i]=10;
      }
      else{
        deck[i]=(i-25);
      }

    }
    for(int i=39; i<52; i++){ //Diamonds
      if(i>47){
        deck[i]=10;
      }
      else{
        deck[i]=(i-38);
      }

    }
}

Then, I also created a shuffleDeck function in the Deck class.

public void shuffleDeck(){
  int[] temp = new int[52];
  int[] indexChecker = new int[52];
  for(int i=0 ; i<52 ; i++){
    indexChecker[i]=0;
  }
  int index = 0;
  for(int i=0; i<52 ; i++){
    index = number.nextInt(52);
    for(i=0; i<52 ; i++){
      while(index == indexChecker[i])
      index = number.nextInt(52);
    }
    temp[i] = deck[index]; //The error is here
  }

  for(int i=0; i<52; i++){
    deck[i] = temp [i];
  }
}

I use this algorithm to make sure that my random index generator does not generate the same number to shuffle my deck.

But when I try to shuffle it in the main class, it doesn't work.

    public static void main(String[] args) {

    Deck card = new Deck();

    System.out.println("Decks are created");
    card.getDeck();

    System.out.println("Shuffling...");
    card.shuffleDeck();

    System.out.println("Shuffled deck.");
    card.getDeck();

The output:

run:
Decks are created
0-1
1-2
2-3
3-4
4-5
5-6
6-7
7-8
8-9
9-10
10-10
11-10
12-10
13-1
14-2
15-3
16-4
17-5
18-6
19-7
20-8
21-9
22-10
23-10
24-10
25-10
26-1
27-2
28-3
29-4
30-5
31-6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52
32-7
33-8
34-9
35-10
36-10
37-10
38-10
39-1
40-2
    at blackjack.pkg5.pkg0.Deck.shuffleDeck(Deck.java:69)
41-3
42-4
43-5
44-6
45-7
    at blackjack.pkg5.pkg0.Blackjack50.main(Blackjack50.java:13)
46-8
47-9
48-10
49-10
50-10
51-10
Shuffling...
C:\Users\Afrie Irham\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

Solution

  •   for(int i=0; i<52 ; i++){
        index = number.nextInt(52);
        for(i=0; i<52 ; i++){
          while(index == indexChecker[i])
          index = number.nextInt(52);
        }
        temp[i] = deck[index]; //The error is here
      }
    

    You are reusing i in the inner loop, thus erasing the old value and incrementing until !(i < 52), i.e. i >= 52, then after the loop you are accessing temp[i], which is out of bounds for i >= 52. So just introduce a new iteration variable j to replace i in the inner loop.