-1

已经有一个名为 Card.java 的类有 52 张卡片。在 Deck.java 中,我必须编写一个构造函数来用套件和值连续初始化 52 张卡。我写了下面的代码,但它没有通过公共测试..有人可以帮我吗?

public class Deck {
    private Card[] cards;
    private final int DECK_SIZE=52;

    public Deck(){
        this.cards=new Card[DECK_SIZE];
        int index = 0;
        for (int suit = 0; suit <= 3; suit++) {
            for (int value = 1; value <= 13; value++) {
                this.cards[index] = new Card (suit, value);
                index++;
            }
        }
    }
    public Deck(Deck other) {
        this.cards= new Card[DECK_SIZE];
        for(int i=1;i<=DECK_SIZE;i++){
            this.cards[i]= other.cards[i];
}
4

3 回答 3

1

在您的第二个构造函数中,您从1DECK_SIZE( 1..52) 进行迭代,但您应该从以下开始迭代0

    for(int i=0; i<DECK_SIZE;i++){
        this.cards[i]= other.cards[i];
    }

你的代码应该抛出ArrayIndexOutOfBoundsException.

于 2011-04-14T00:28:51.720 回答
0

你的 for 循环,

for(int i=1;i<=DECK_SIZE;i++){

不正确,应该读

for(int i=0;i <DECK_SIZE;i++){

一个大小为 52 的数组只有从 0 到 51 的索引。

于 2011-04-14T00:28:21.630 回答
0

Java 教程中有一个很好的示例,说明了使用枚举值创建卡片组的方法:http: //download.oracle.com/javase/1.5.0/docs/guide/language/enums.html

在 java 中做数组的传统方法是for (int i = 0; i < XXX; i++). 您应该将您的 Suit 循环更改为<4not <=3,并且您的 Deck 在第二个构造函数中查找为 be for (int i = 0; i < DECK_SIZE; i++)。长度为 n 的数组从索引 0 开始,到索引 n-1 结束。

一副牌可以少于 52 张牌吗?在这种情况下,您的第二个构造函数可能会抛出某种异常;因为它会给出一个ArrayIndexOutOfBoundsException.

于 2011-04-14T00:38:48.663 回答