简体   繁体   中英

toString method of a class

I have a card class that looks like this:

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

And another Deck class that uses the Card class to create an array:

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

My toString method is giving me the error "cannot find symbol - method getFaceValue()". Same for getSuit(). Any ideas why?

deck is an array of Card[] deck . Hence, you can't call the method getFaceValue() nor getSuit() on it, because those 2 methods are part of the Card class and NOT of the array of Cards.

here some possible solutions to your problem as suggested:

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

or for loop through the entire deck

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

    return deckInStringForm;
}

or change/add a function to take an index like so

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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