【问题标题】:toString method of a class类的 toString 方法
【发布时间】:2017-05-25 13:01:17
【问题描述】:

我有一个如下所示的卡片类:

public class Card
{
    //instance variables
    private String faceValue; //the face value of the card
    private String suit; //the suit of the card
    String[] ranks = {"Ace", "2", "3", "4", "5", "6","7", "8", "9", "10", "Jack", "Queen", "King"};
    String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};

    /**
     * Constructor
     */
    public Card()
    {
        for (int i = 0; i < 13; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                faceValue = ranks[i];
                suit = suits[j];
            }
        }
    }

    //getters
    /**
     * Getter for faceValue.
     */
    public String getFaceValue()
    {
        return faceValue;
    }

    /**
     * Getter for suit.
     */
    public String getSuit()
    {
        return suit;
    }
    //end of getters

    //methods
    /**
     * This method returns a String representation of a Card object.
     * 
     * @param   none
     * @return  String 
     */
    public String toString()
    {
        return "Dealed a card: " + faceValue + " of " + suit;
    }
}

还有另一个使用 Card 类创建数组的 Deck 类:

public class Deck
{
    //instance variables
    private Card[] deck;

    /**
     * Constructor for objects of class Deck
     */
    public Deck() 
    {
        deck = new Card[52];
    }

    /**
     * String representation.
     */
    public String toString()
    {
        return "Dealed a card: " + deck.getFaceValue() + " of " + deck.getSuit();
    }
}

我的 toString 方法给了我错误“找不到符号 - 方法 getFaceValue()”。 getSuit() 也一样。任何想法为什么?

【问题讨论】:

  • deckCard 数组,而不是 Card。数组没有这两种方法。
  • 数组没有方法。数组元素有方法。
  • 您可以简单地返回Arrays.toString(deck),这将给出所有卡片字符串的列表。
  • 完全不相关,但一张牌的toString 不应该包含任何关于它被处理的信息——它只是一张纸牌的人类代表。对卡片所做的/已经完成的事情是一个单独的问题。
  • 卡片构造函数中嵌套的do循环的目的是什么?你确实意识到任何调用new Card() 的结果都会生成一张黑桃K,不是吗?

标签: java arrays string methods


【解决方案1】:

deckCard[] deck 的数组。因此,您不能对其调用方法 getFaceValue() 或 getSuit(),因为这两个方法是 Card 类的一部分,而不是 Cards 数组的一部分。

【讨论】:

    【解决方案2】:

    这里有一些可能解决您问题的建议:

    public String toString()
    {
        return Arrays.toString(deck);
    }
    

    或 for 循环遍历整个卡组

    public String toString()
    {
        String deckInStringForm = "[ ";
        for(int indexOfCard = 0; indexOfCard < deck.length; indexOfCard++)
        {
            deckInStringForm += deck[indexOfCard] + " ";
        }
        deckInStringForm += "]";
    
        return deckInStringForm;
    }
    

    或更改/添加一个函数来获取这样的索引

    public String toString(int index)
    {
       return "Card " + index + ": " + deck[index].toString();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 2016-07-21
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 2017-05-24
      相关资源
      最近更新 更多