我在Class Deck中有ArrayList牌组。我想用Card对象填充ArrayList。
另外我想填充Card对象的属性。
我添加了一个for循环来查看结果,而ArrayList有5个对象,其名称为NULL,值为0。
(已在主要功能中调用FillDeck)
import java.util.ArrayList;
public class Deck {
private ArrayList<Card> deck=new ArrayList();
public Deck(){
}
public Deck(ArrayList<Card> deck ){
this.deck = deck;
}
//hearts,spades,diamonds,clubs
Card card1 = new Card("A hearts",11,true);
Card card2 = new Card("2 hearts",2,true);
Card card3 = new Card("3 hearts",3,true);
Card card4 = new Card("4 hearts",4,true);
Card card5 = new Card("5 hearts",5,true);
public void filldeck(){
deck.add(card1);
deck.add(card2);
deck.add(card3);
deck.add(card4);
deck.add(card5);
for (int i=0; i<deck.size(); i++){
System.out.println(deck.get(i).getName());
System.out.println(deck.get(i).getValue());
}
}
}
public class Card {
private String name;
private int value;
private boolean samecard = true ;
public Card(){
}
public Card(String name,int value,boolean samecard){
name = this.name;
value = this.value;
samecard = this.samecard;
}
public String getName(){
return name;
}
public int getValue(){
return value;
}
public boolean getSamecard(){
return samecard;
}
}
答案 0 :(得分:3)
因为您看到了字段的默认值。要解决这个问题,你必须实际分配值,例如
public Card(String name,int value,boolean samecard){
this.name = name;
this.value = value;
this.samecard = samecard;
}
答案 1 :(得分:2)
您的Card(String name, int value, boolean samecard)
执行错误,您无法将实例变量分配给构造函数参数。
要明确这是错误的:name = this.name
这是正确的:this.name = name
这是一个正确的实施:
public Card(String name,int value,boolean samecard){
this.name = name;
this.value = value;
this.samecard = samecard;
}
答案 2 :(得分:1)
你搞砸了Card类中的构造函数,将构造函数变量赋值改为:
this.name = name;
this.value = value;
this.samecard = samecard;
答案 3 :(得分:0)
您的承包商有问题。它看起来像这样:
public Card(String name,int value,boolean samecard){
name = this.name;
value = this.value;
samecard = this.samecard;
}
它应该是这样的:
public Card(String name,int value,boolean samecard){
this.name = name;
this.value = value;
this.samecard = samecard;
}
答案 4 :(得分:0)
你是qualifying作业的右侧,在这种情况下是错误的:
public Card(String name,int value,boolean samecard){
name = this.name;
value = this.value;
samecard = this.samecard;
}
一定是
public Card(String name,int value,boolean samecard){
this.name = name;
this.value = value;
this.samecard = samecard;
}