【问题标题】:Dealing 7 random non-repeating "cards" out of a deck of 52从一副 52 张牌中随机发 7 张不重复的“牌”
【发布时间】: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


【解决方案1】:

你的最后一个 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());
}

【讨论】:

  • 啊哈!那解决了它!感谢您指出这一点——我认为您必须使用 k 来随机获得 52 张卡中的一张,但我现在知道它是如何工作的。这真的更像是在甲板上“交易”。完美的!非常感谢!
  • ^^ 是的,此时 K 等于 52,这就是为什么您会看到 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52,因为数组的最大索引是 51
  • @uhurulol 将迭代器留在使用它们的循环中的原因之一。例如for (int j = 0; 如果您为 k 执行此操作,您将不会收到此错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多