簡體   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