[英]Java: How to use the toString() method of one class in an other one?
I'm working on this project while learning Java, I created a Card
class that has a toString() method but when I'm trying to convert a Card
object to a String in the Deck
class I'm getting an error . 我在学习Java时正在从事这个项目,我创建了一个具有toString()方法的
Card
类,但是当我尝试在Deck
类中将Card
对象转换为String时,却遇到了错误 。
Here is the Card class:
这是Card类:
private final Rank cardRank;
private final Suit cardSuit;
public Card(Rank cardRank, Suit cardSuit){
this.cardRank = cardRank;
this.cardSuit = cardSuit;
}
public String toString(){
return "The " + cardRank + " of " + cardSuit;
}
Here is the Deck class:
这是Deck类:
private Card[] card = new Card[52];
public Deck(){
int i = 0;
for(Suit suit: Suit.values()){
for(Rank rank: Rank.values()){
card[i++] = (new Card(rank, suit));
}
}
}
public String toString(int i){
return card[i];
}
You can't cast a Card
object into String
object. 您不能将
Card
对象转换为String
对象。
You can get the String
representation of the Card
object through toString()
method. 您可以通过
toString()
方法获取Card
对象的String
表示形式。
Try like below 尝试如下
public String toString(int i){
return card[i].toString();
}
Calling return card[i] returns an object of type card. 调用返回卡[i]返回卡类型的对象。 You have to actually call the toString() method so that your return object is a String and not a Card.
您必须实际调用toString()方法,以便您的返回对象是String而不是Card。 Hope this helps!
希望这可以帮助!
If the toString()
of each of your class does not have the @Override
annotation, then you have to explicitly call the toString()
. 如果每个类的
toString()
没有@Override
批注,则必须显式调用toString()
。
Example: 例:
return card[i].toString();
return "The " + cardRank.toString() + " of " + cardSuit.toString;
If you add the @Override
annotation like this: 如果您像这样添加
@Override
注释:
@Override
public String toString(){
return "The " + cardRank.toString() + " of " + cardSuit.toString();
}
Then the Deck class toString(int i)
can look like: 然后,Deck类
toString(int i)
可以看起来像:
public String toString(int i){
return card[i];
}
If you add the @Override
to the Rank
and Suit
class, then the Card
class toString()
can look like: 如果将
@Override
添加到Rank
and Suit
类,则Card
类toString()
可能类似于:
public String toString(){
return "The " + cardRank + " of " + cardSuit;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.