对象覆盖堆栈(Java)

时间:2013-09-06 02:17:27

标签: java object stack

我正在尝试编写一个显示卡片中所有卡片的代码。不幸的是,添加到堆栈中的最后一张卡似乎一直在覆盖以前输入的所有卡片。我怎样才能防止这种情况发生?现在,当我输入代码时,它只显示“黑桃王牌”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;
    }
}

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:0)

在声明变量值和套装时,您应该使用静态

您可以使用私有字符串值声明这些值; private String suit; 生成了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;
    }

}