【问题标题】:How do I store an instance of a class created by a constructor so variables within in can be called later?如何存储由构造函数创建的类的实例,以便稍后可以调用 in 中的变量?
【发布时间】:2014-03-12 15:37:08
【问题描述】:

例如:我有一副纸牌,有一个构造函数 Card(char,int)。我初始化了 52 个卡片实例。然后使用 Card 中的一个方法,我调用 GetName(),它应该返回一个 char + int 字符串;因此,如果我将其初始化为 Card c1 = new Card(d,1);并调用 c1.GetName();它应该返回 c1。但是,该程序正在选择不同的卡并分配该名称的所有卡实例。

The Code is rather long so I have it copied here: http://pastebin.com/7akeFgs0

我已经查看了垃圾收集,但如果这是问题,我不知道该怎么办。

【问题讨论】:

    标签: java arrays constructor initialization


    【解决方案1】:

    您的变量 Name、Flip 和 SuitNumber 不应是静态的。否则,您的所有实例只有一个 Name、Flip 和 SuitNumber。

    顺便说一句,它们也应该以小写字母开头,但这与问题无关。

    【讨论】:

    • 天哪,就这么简单。我正在检查所有复杂的解决方案,甚至懒得检查...
    【解决方案2】:

    在你的构造函数中

    public Card(int Suitnumber, int Number){
                     SuitNumber = Suitnumber;}
    

    你不要使用第二个参数!

    【讨论】:

      【解决方案3】:

      在java中charsints所以char + int = int。你可能想要的是"" + char + int;,它返回一个字符串。

      另外,你真的让套牌生成过于复杂了。我会建议这样的事情:

      public class Card
      {
      
          char suit;
          int value;
      
          public Card(char suit, int value)
          {
              this.suit = suit;
              this.value = value;
          }
      
          public String getName()
          {
              return "" + suit + value;
          }
      }
      

      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.List;
      
      
      public class Deck
      {
      
          static final char[] suits = new char[] {
                  'h', 'd', 'c', 's'
          };
          static final int[] values = new int[] {
                  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
          };
      
          List<Card> cards;
      
          public Deck()
          {
              cards = new ArrayList<Card>();
              for (char suit : suits)
              {
                  for (int value : values)
                  {
                      cards.add(new Card(suit, value));
                  }
              }
          }
      
          public void shuffle()
          {
              Collections.shuffle(cards);
          }
      }
      

      您还可以考虑使用 Java Enums 来制作套装。它将允许轻松比较,并为每个西装提供一个人类可读的字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-17
        • 2020-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多