如何将对象添加到数组并打印它?

时间:2016-02-18 04:36:34

标签: java arrays object

我试图建立一个人类可以从主类中添加对象的甲板类。让我们在我的子类中说,我有一个名为public void add(Object n)的方法 然后在我的主要课程中,我添加了objects等牌"黑桃""心","钻石""俱乐部"等等  它应该打印出甲板。 这是我的方法类的代码。我还没有制定这个方法,但是在deck2中它将等于n。 所以当有人add.("Spades")时,它会将其添加到甲板上。

 Object [] deck=new Object[52];
        Object [] Suits=new Object[4];
        Object [] Ranks=new Object[17];
        Object deck2[]={"Spades","Hearts","Diamonds","Clubs","2","3","4","5","6","7","8","9","10","Jack","King","Queen","Ace"};
        for(int i=0;i<4;i++){
            Suits[i]=deck2[i];

        }
            for(int i=4;i<Ranks.length;i++){
                Ranks[i]=deck2[i];
            System.out.println(Ranks[i]);
        }

            for(int i=0;i<deck.length;i++){
                deck[i]=Ranks[i%13]+" "+"of "+Suits[i/13];
            System.out.println(deck[i]);

}}}

它应该提供与此相同的输出。这是分开的,但在我尝试创建的方法中。我只能有一个对象。

Object [] deck2=new Object [52];
        Object[] deck=new Object [52];

        Object suits[]={"Spades","Hearts","Diamonds","Clubs"};
        Object rank[]={"2","3","4","5","6","7","8","9","10","Jack","King","Queen","Ace"};
        System.out.println("               Normal Deck");
        for(int i=0;i<deck.length;i++){
            deck[i]=rank[i%13]+" "+"of "+suits[i/13];
            deck2[i]=deck[i];
            System.out.println(deck[i]+",");}

1 个答案:

答案 0 :(得分:0)

好吧,对象数组和对象数组之间存在差异 &#34;对象&#34;是所有java对象的超类 很可能你的任务是指对象而不是&#34;对象&#34;类。
所以首先创建一个名为Card的类。

class Card
{
  private String rank;
  private String suit;

  public Card(String suit, String rank)
  {
    this.suit = suit;
    this.rank = rank;
  }

  //Add getter methods

  @Override
  public String toString()
  {
    return ("Suit :" + suit + " and Rank :" + rank);
  }
}

现在在你的主要方法中 创建卡对象的ArrayList 喜欢这个

ArrayList<Card> cards = new ArrayList<Card>();

创建卡片对象并将其添加到列表中 例如

cards.add(new Card("Heart", "10"));
cards.add(new Card("Spades", "King"));

填充ArrayList后,打印所有卡对象。

for(Card card: cards)
{
  System.out.println(card.toString());
}