[英]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:另一个使用 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();
}
}
My toString method is giving me the error "cannot find symbol - method getFaceValue()".我的 toString 方法给了我错误“找不到符号 - 方法 getFaceValue()”。 Same for getSuit().
getSuit() 也一样。 Any ideas why?
任何想法为什么?
deck
is an array of Card[] deck
. deck
是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.因此,您不能对其调用 getFaceValue() 或 getSuit() 方法,因为这两个方法是 Card 类的一部分,而不是 Cards 数组的一部分。
here some possible solutions to your problem as suggested:根据建议,这里有一些可能的解决方案:
public String toString()
{
return Arrays.toString(deck);
}
or for loop through the entire deck或 for 循环整个甲板
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.