Dealing 7 random non-repeating “cards” out of a de

2019-07-25 04:21发布

问题:

With the help of this forum I've designed a program to simulate a deck of cards. The final class in the program is meant to give two options: Option 1 will display the 52 cards, and option 2 will deal out 7 random (nonrepeating) cards. I'm using Collections.shuffle for this, but I'm getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52 when I select option 2 (the program works and compiles fine otherwise).

Here is the class---let me know if you need any information about the other methods:

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

}

Stack trace:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52 at CardTester.main(CardTester.java:93)

回答1:

Your last for loop has a minor mistake:

for(int j = 0; j < 7; j++) {
    //Random rand = new Random ();
    System.out.println(newDeck.getCard(deal[k]).whatCard());
                                          //^// that is not j
}

change it to

for(int j = 0; j < 7; j++) {
    //Random rand = new Random ();
    System.out.println(newDeck.getCard(deal[j]).whatCard());
}