1

我正在尝试编写一个代码来显示一副牌中的所有卡片。不幸的是,最后添加到堆栈中的卡似乎一直覆盖所有先前输入的卡。我怎样才能防止这种情况发生?现在,当我输入代码时,它只会显示“黑桃 A”这一行 52 次。

import java.util.*;

public class cardSearcher{

public static void main(String[] args){
 Stack<card> deck = new Stack<card>();
 String[] value = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
 String[] suit = {"Diamonds","Hearts","Clubs","Spades"};

for (int i=0;i<value.length;i++){
  for (int j=0;j<suit.length;j++){
        deck.push(new card(value[i],suit[j]));
  }
}

while (!deck.empty()){
  card chosenCard = deck.pop();
  System.out.println(chosenCard.value +" of "+ chosenCard.suit);
  }
 }
}

这是卡代码:

public class card {

    public static String value = "";
    public static String suit = "";

    public card(String valueofCard, String suitofCard) {
        card.value = valueofCard;
        card.suit = suitofCard;
    }
}
4

2 回答 2

7

static属于整个类的变量,而不是任何实例。当您修改这些时,您正在修改在所有实例之间共享的变量。删除static变量上的修饰符以使它们针对每个实例进行个性化。

于 2013-09-06T02:22:42.787 回答
0

在声明 value 和 suit 的变量时,您应该使用static 。

您可以使用私有字符串值声明这些值;私人弦乐套装;生成了getter/setter。

这样做,您可以获得预期的结果。

import java.util.Stack;

public class cardSearcher {

    public static void main(String[] args) {
        Stack<card> deck = new Stack<card>();
        String[] value = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
                "Jack", "Queen", "King", "Ace" };
        String[] suit = { "Diamonds", "Hearts", "Clubs", "Spades" };

        for (int i = 0; i < value.length; i++) {
            for (int j = 0; j < suit.length; j++) {
                deck.push(new card(value[i], suit[j]));
            }
        }

        while (!deck.empty()) {
            card chosenCard = deck.pop();
            System.out.println(chosenCard.getValue() + " of "
                    + chosenCard.getSuit());
        }
    }
}

class card {
    private String value;

    private String suit;

    /**
     * @param value
     * @param suit
     */
    public card(String value, String suit) {
        this.value = value;
        this.suit = suit;
    }

    /**
     * @return the value
     */
    public String getValue() {
        return value;
    }

    /**
     * @param value
     *            the value to set
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * @return the suit
     */
    public String getSuit() {
        return suit;
    }

    /**
     * @param suit
     *            the suit to set
     */
    public void setSuit(String suit) {
        this.suit = suit;
    }

}
于 2013-09-06T02:32:20.537 回答