我在Class Deck中有ArrayList套牌。我想用Card对象填充ArrayList。
我还想填充卡片对象的属性。
我添加了一个 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;
}
}
因为您看到的是字段的默认值。要解决此问题,您必须实际分配值,例如
public Card(String name,int value,boolean samecard){
this.name = name;
this.value = value;
this.samecard = samecard;
}
您的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;
}
你在 Card 类中搞砸了构造函数,将构造函数变量赋值更改为:
this.name = name;
this.value = value;
this.samecard = samecard;
您正在限定作业的右侧,在这种情况下是不正确的:
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;
}
您的承包商有问题。它看起来像这样:
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;
}