我正在编写这个方法来创建一副洗过的纸牌:
public static ArrayList<String> shuffle() {
String cards[] = {"Two of Spades","Three of Spades","Four of Spades","Five of Spades", "Six of Spades","Seven of Spades", "Eight of Spades", "Nine of Spades", "Ten of Spades", "Jack of Spades", "Queen of Spades", "King of Spades", "Ace of Spades",
"Two of Hearts","Three of Hearts","Four of Hearts","Five of Hearts", "Six of Hearts","Seven of Hearts", "Eight of Hearts", "Nine of Hearts", "Ten of Hearts", "Jack of Hearts", "Queen of Hearts", "King of Hearts", "Ace of Hearts",
"Two of Clubs","Three of Clubs","Four of Clubs","Five of Clubs", "Six of Clubs","Seven of Clubs", "Eight of Clubs", "Nine of Clubs", "Ten of Clubs", "Jack of Clubs", "Queen of Clubs", "King of Clubs", "Ace of Clubs",
"Two of Diamonds","Three of Diamonds","Four of Diamonds","Five of Diamonds", "Six of Diamonds","Seven of Diamonds", "Eight of Diamonds", "Nine of Diamonds", "Ten of Diamonds", "Jack of Diamonds", "Queen of Diamonds", "King of Diamonds", "Ace of Diamonds" };
ArrayList<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < 52; i++) {
numbers.add(i);
}
ArrayList<String> deck = new ArrayList<String>();
for (int i = 0; i < 52; i++) {
Random randomizer = new Random();
int index = randomizer.nextInt(numbers.size());
int number = numbers.get(index);
deck.add(numbers.get(number), cards[i]);
numbers.remove(index);
}
return deck;
}
我遇到的问题是在deck.add时,出现了IndexOutOfBoundsException异常。我原以为ArrayList会自动调整大小以适应添加元素,为什么会发生这种情况,怎么解决呢?以下是异常信息:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 23, Size: 0
at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
at java.util.ArrayList.add(ArrayList.java:473)
at game.mainGame.shuffle(mainGame.java:182)
at game.mainGame.main(mainGame.java:32)
deck.add
、numbers.get(number)
还是cards[i]
引起的。它一定是其中之一,但我们很难神奇地看出哪一个。 - JamesENLCollections.shuffle()
会为你节省很多麻烦 ;) - QBrute