在这个论坛的帮助下,我设计了一个模拟一副牌的程序。该计划的最后一课旨在提供两个选项:选项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)
答案 0 :(得分:4)
你的最后一个for循环有一个小错误:
for(int j = 0; j < 7; j++) {
//Random rand = new Random ();
System.out.println(newDeck.getCard(deal[k]).whatCard());
//^// that is not j
}
将其更改为
for(int j = 0; j < 7; j++) {
//Random rand = new Random ();
System.out.println(newDeck.getCard(deal[j]).whatCard());
}