我不明白为什么它说 ArrayOutOfBound 错误

I don't understand why it says ArrayOutOfBound error

我正在尝试制作二十一点游戏。

首先,我使用 class 构造函数创建了一个名为 deck size 52 的数组。

    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);
      }

    }
}

然后,我也在Deck中创建了一个shuffleDeck函数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];
  }
}

我使用这个算法来确保我的随机索引生成器不会生成相同的数字来洗牌。

但是当我尝试在主 class 中随机播放它时,它不起作用。

    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();

输出:

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.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
  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
  }

您正在内部循环中重复使用 i,从而擦除旧值并递增直到 !(i < 52),即 i >= 52,然后在循环之后您正在访问 temp[i],这超出了 i >= 52 的范围。所以只要引入一个新的迭代变量j来代替内循环中的i