所以我有一個卡類,看起來像這樣:在一個toString類Return語句
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(int aValue, int aSuit)
{
faceValue = ranks[aValue];
suit = suits[aSuit];
}
//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 "A card: " + faceValue + " of " + suit;
}
}
而且甲板類,看起來像這樣:在甲板上表演
public class Deck
{
//instance variables
private Card[] deck;
/**
* Constructor for objects of class Deck
*/
public Deck()
{
deck = new Card[52];
int cardCount = 0; //number of cards created so far.
for (int aSuit = 0; aSuit < 4; aSuit++)
{
for (int aValue = 0; aValue < 13; aValue++) {
deck[cardCount] = new Test(aValue, aSuit);
cardCount++;
}
}
}
/**
* String representation.
*/
public String toString()
{
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
return "Dealt a card: " + v + " of " + s + ".";
}
}
}
我的toString方法錯誤「缺少返回語句」。如何更改退貨聲明,同時仍然允許它在每次循環後打印卡片細節?
如果你返回一個循環,你只會得到列表的第一個元素 –
你應該閱讀'toString()'上的JavaDoc來查看wh (它不會產生日誌語句),因爲它是單個卡的表示,但是'Deck.toString()'不是'因爲它不會' t代表甲板,而是一些動作(或者至少是「應對卡片......」意味着如此)。相反,您可能需要提供一種方法,可以直接打印日誌語句或返回一個字符串列表供以後使用。 – Thomas
首先,即使你沒有這個錯誤,你的toString也不會做你想做的事。您需要創建一個聚合該字符串的變量,並在函數結束時返回一次。就像它將在循環的第一次迭代中運行並返回一樣。 – Rob