繁体   English   中英

类的 toString 方法

[英]toString method of a class

我有一个看起来像这样的卡片类:

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

根据建议,这里有一些可能的解决方案:

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM