将对象添加到java中的arraylist [英] Adding objects to an arraylist in java

查看:37
本文介绍了将对象添加到java中的arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Java 上编写一个纸牌游戏.我正在尝试将卡片对象添加到我的数组列表中,但 MakeDeck 函数无法正常工作.

I am trying to write a solitiare game on java. I'm trying to add the card objects to my arraylist but the MakeDeck function is not working properly.

public class PileOfCards {
public ArrayList<Card> pile = new ArrayList<Card>();
Card tempo;

public PileOfCards() {
  pile = new ArrayList<Card>();

}

public void MakeDeck() {

    for (int i=0;i<13;i++){
        tempo = new Card(i+1, "FaceDown", "Clubs");
        pile.add(tempo);

    }
    for (int j=0;j<13;j++){
        tempo = new Card(j+1, "FaceDown", "Diamonds");
        pile.add(tempo);
}
    for (int k=0;k<13;k++){
        tempo = new Card(k+1, "FaceDown", "Hearts");
        pile.add(tempo);
    }
    for (int l=0;l<13;l++){
        tempo = new Card(l+1, "FaceDown", "Spades");
        pile.add(tempo);
    }
} 

当我尝试打印值时,它会打印 "0, null, null" 52 次.问题是什么?看起来我无法访问 ArrayList,但我不知道为什么.

When I'm trying to print the values it prints "0, null, null" , 52 times. What is the problem? It looks like I can't reach to the ArrayList, but I don't know why.

卡片构造函数:

   public Card(int valueTemp, String suitTemp, String statusTemp) {
    valueTemp = value;
    suitTemp = suit;
    statusTemp = status;
    }

打印功能:

 public void printPile(){
     for(int i=0;i<pile.size();i++){
     System.out.print(pile.get(i).status);
     System.out.print(" ");
     System.out.print(pile.get(i).suit);
     System.out.print(" ");
     System.out.print(pile.get(i).value);
     System.out.printf("\n");
 }

推荐答案

问题出在您的 Card 构造函数中;分配方式不对.

The issue is in your Card constructor; the assignments are the wrong way around.

你想要

public Card(int valueTemp, String suitTemp, String statusTemp) {
    value = valueTemp;
    suit = suitTemp;
    status = statusTemp;
}

相反,不会将字段设置为等于参数,而是将参数设置为等于字段.具体来说,你之前有什么

The other way around doesn't set the fields equal to the parameters, it sets the parameters equal to the fields. Specifically, what you had before

public Card(int valueTemp, String suitTemp, String statusTemp) {
   valueTemp = value;
   suitTemp = suit;
   statusTemp = status;
}

设置 valueTempvaluesuitTempsuitstatusTempstatus,当你真的想在你的构造函数中做相反的事情时.

sets valueTemp to value, suitTemp to suit, and statusTemp to status, when you actually wanted to do the other way around in your constructor.

这篇关于将对象添加到java中的arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆