目前,我正在尝试通过使用for循环来获取每张卡,以一副纸牌填充ArrayList。它并没有按照我的预期工作,而是希望有人指出我正确的方向。

我看到以下错误:

System.ArgumentOutOfRangeException: The value must be greater than or equal to zero and less than the console's buffer size in that dimension.


我的甲板课程:

public class Deck{
    private final int deckSize = 52;
    private final String[] suit = {"hearts", "clubs", "diamonds", "spades"};
    private final String[] face = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};


    ArrayList<String> currentDeck = new ArrayList<String>(deckSize);


    public void getDeck(){
        for(int i=0; i<face.length; i++) {
            for(int j=0; j<suit.length; j++){
                String cards = face[i] + " of " + suit[j];
                currentDeck.add(cards);
            }
        }
    System.out.println(currentDeck);
    }
}


主班



    public static void main(String[] args) {
        printDeck();
    }

    public static void printDeck(){
        Deck deck = new Deck();
        deck.getDeck();
    }

最佳答案

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        Deck deck = new Deck();
        deck.getDeck();
    }
}

class Deck {
    private final int deckSize = 52;
    private final String[] suit = {"hearts", "clubs", "diamonds", "spades"};
    private final String[] face = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};


    ArrayList<String> currentDeck = new ArrayList<String>(deckSize);


    public void getDeck() {
        for (int i = 0; i < face.length; i++) {
            for (int j = 0; j < suit.length; j++) {
                String cards = face[i] + " of " + suit[j];
                currentDeck.add(cards);
            }
        }
        System.out.println(currentDeck);
    }
}


我只复制了您的代码,所以此代码运行正常。我刚刚添加了main方法,并调用了您的方法。而且,我得到的输出是

[1 of hearts, 1 of clubs, 1 of diamonds, 1 of spades, 2 of hearts, 2 of clubs, 2 of diamonds, 2 of spades, 3 of hearts, 3 of clubs, 3 of diamonds, 3 of spades, 4 of hearts, 4 of clubs, 4 of diamonds, 4 of spades, 5 of hearts, 5 of clubs, 5 of diamonds, 5 of spades, 6 of hearts, 6 of clubs, 6 of diamonds, 6 of spades, 7 of hearts, 7 of clubs, 7 of diamonds, 7 of spades, 8 of hearts, 8 of clubs, 8 of diamonds, 8 of spades, 9 of hearts, 9 of clubs, 9 of diamonds, 9 of spades, 10 of hearts, 10 of clubs, 10 of diamonds, 10 of spades, Jack of hearts, Jack of clubs, Jack of diamonds, Jack of spades, Queen of hearts, Queen of clubs, Queen of diamonds, Queen of spades, King of hearts, King of clubs, King of diamonds, King of spades]


我相信这就是您想要的。

09-10 00:58