我正在制作纸牌游戏并尝试使用由两个字符串元素组成的Card对象:卡片和套装的价值,以及创建这些卡片对象的ArrayList。我已经尝试使用下面的代码,并注意到每次我添加一个新元素,我看到每个元素都被更改为与最近添加的元素具有相同的数据 这是我的代码:
import java.util.*;
public class testArrayList
{
public static void main(String args[])
{
ArrayList<Card> deck= new ArrayList<Card>();
String cValues[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
int cVLength= cValues.length;
String cSuit[] = {"Hearts", "Diamonds", "Clubs", "Spades"};
int cSLength= cSuit.length;
for(int k=0; k<cVLength; k++)
{
for(int j=0; j<cSLength; j++)
{
deck.add(new Card(cValues[k],cSuit[j]);
}
}
System.out.println(deck.get(0).getValue()+ " "+ deck.get(0).getSuit());
System.out.println(deck.get(1).getValue()+ " "+ deck.get(1).getSuit());
System.out.println(deck.get(50).getValue()+ " "+ deck.get(50).getSuit());
System.out.println(deck.get(51).getValue()+ " "+ deck.get(51).getSuit());
}
}
class Card
{
private static String value;
private static String suit;
public Card(String v, String s)
{
value = v;
suit = s;
}
public static String getValue()
{
return value;
}
public static String getSuit()
{
return suit;
}
}
请帮助任何非常感谢!
答案 0 :(得分:2)
你的班级Card
有一个致命的缺陷,它只有静态字段。
class Card
{
private String value; // <-- not static
private String suit; // <-- not static
public Card(String v, String s)
{
this.value = v; // <-- really not static.
this.suit = s;
}
public String getValue() // <-- also not static.
{
return value;
}
public String getSuit()
{
return suit;
}
}
答案 1 :(得分:2)
问题不在于您ArrayList
,问题在于您Card
类......
private static String value;
private static String suit;
基本上意味着无论您将其设置为什么值,它都会针对Card
的每个实例进行更改
删除static
声明,例如
class Card {
private String value;
private String suit;
public Card(String v, String s) {
value = v;
suit = s;
}
public String getValue() {
return value;
}
public String getSuit() {
return suit;
}
}
使用您的示例运行它时,它现在输出...
Ace Hearts
Ace Diamonds
King Clubs
King Spades