toString类的方法

时间:2017-01-10 21:46:09

标签: java arrays string methods

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

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方法给了我错误&#34;找不到符号 - 方法getFaceValue()&#34;。对于getSuit()也是如此。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

deckCard[] deck的数组。因此,你不能在它上面调用方法getFaceValue()和getSuit(),因为这两个方法是Card类的一部分,而不是卡数组的一部分。

答案 1 :(得分:0)

这里建议您解决问题的一些方法:

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

或循环通过整个牌组

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