【发布时间】:2017-05-25 13:01:17
【问题描述】:
我有一个如下所示的卡片类:
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() 也一样。任何想法为什么?
【问题讨论】:
-
deck是Card数组,而不是Card。数组没有这两种方法。 -
数组没有方法。数组元素有方法。
-
您可以简单地返回
Arrays.toString(deck),这将给出所有卡片字符串的列表。 -
完全不相关,但一张牌的
toString不应该包含任何关于它被处理的信息——它只是一张纸牌的人类代表。对卡片所做的/已经完成的事情是一个单独的问题。 -
卡片构造函数中嵌套的do循环的目的是什么?你确实意识到任何调用
new Card()的结果都会生成一张黑桃K,不是吗?
标签: java arrays string methods