在toString类中返回语句

时间:2017-01-13 13:51:40

标签: java

所以我有一个看起来像这样的Card类:

for i in range(64):
    img_final += get_image(x,y)

一个看起来像这样的Deck类:

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

套牌中我的toString方法显示错误"缺少返回语句"。如何更改return语句,同时仍允许它在每次循环后打印卡片详细信息?

3 个答案:

答案 0 :(得分:2)

您编写的代码只会从deck数组中返回第0个元素。它应该是:

public String toString()
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 52; i++)
    {
        String v = deck[i].getFaceValue();
        String s = deck[i].getSuit();
        sb.append("Dealt a card: ").append(v).append(" of ").append(s).append(".\n");
    }
    return sb.toString();
}

答案 1 :(得分:0)

错误是因为您的toString方法的返回类型为String Java检查执行路径。如果for循环结束并且从不返回任何内容怎么办?

虽然您可能已经硬编码了那个逻辑,但是Java编译器并没有对其进行统计分析。因此,它必须返回一个类型String,如果没有其他工作,它肯定会执行。

这将有效:

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 + ".";
    }
    return "";
}

但我猜你想要的是这个:

public String toString()
{
    StringBuilder returnValue = new StringBuilder("");
    for (int i = 0; i < 52; i++)
    {
        String v = deck[i].getFaceValue();
        String s = deck[i].getSuit();
        returnValue.append("Dealt a card: " + v + " of " + s + ".");
    }
    return returnValue.toString();
}

答案 2 :(得分:0)

如果您只想打印所有卡片信息,可以使用

public String toString(){
    for (int i = 0; i < 52; i++)
    {
    String v = deck[i].getFaceValue();
    String s = deck[i].getSuit();
    System.out.println( "Dealt a card: " + v + " of " + s + ".");
    }
    return null;
}