【发布时间】:2015-05-05 20:34:14
【问题描述】:
在这个论坛的帮助下,我设计了一个程序来模拟一副纸牌。程序中的最后一个类旨在提供两个选项:选项 1 将显示 52 张牌,选项 2 将分发 7 张随机(非重复)牌。我为此使用Collections.shuffle,但是当我选择选项2时我得到Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52(否则程序可以正常工作并且编译良好)。
这是课程---如果您需要有关其他方法的任何信息,请告诉我:
public class CardTester {
public static void main(String[] args){
Deck newDeck = new Deck();
System.out.println("Welcome to CardTester! Type 1 to test the deck or type 2 to deal a hand:");
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
if (option == 1) {
for(int i = 0; i < Deck.ncard; i++) {
System.out.println(newDeck.getCard(i).whatCard());
}
} else if (option == 2) {
int k = 0;
Integer[] deal = new Integer[52];
for (k = 0; k < deal.length; k++) {
deal[k] = k;
}
Collections.shuffle(Arrays.asList(deal));
for(int j = 0; j < 7; j++) {
//Random rand = new Random ();
System.out.println(newDeck.getCard(deal[k]).whatCard());
}
}
}
}
堆栈跟踪:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52 at CardTester.main(CardTester.java:93)
【问题讨论】:
-
请添加完整的堆栈跟踪
-
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52 at CardTester.main(CardTester.java:93)请注意,第 93 行对应于System.out.println(newDeck.getCard(deal[k])....的行
标签: java arrays random collections shuffle