从卡的 toString() 获取错误的字符串

Getting wrong string from the toString() of the card

当我试图调试一个非常奇怪的并发症时,当我试图从上一轮失败者那里得到他排名最高的牌并将它拿到我手上时发生。

public Card highestRankingCard()
{
    Collections.sort(getHand());

    Card temp = hand.get(hand.size() - 1);

    return temp;
}

打印到 JOptionPane 时,我得到了一套与我手头完全不相关的西装。

JOptionPane.showMessageDialog(null, "You was the first place in last round and " + game.scores().lastRoundLoser().getName() + " was the last.\n Choose a card of rank 3 - 10 to swap with his highest ranking card.\n" + game.scores().lastRoundLoser().getName() + " has given you " + game.scores().lastRoundLoser().highestRankingCard().toString(), "Swap cards", JOptionPane.INFORMATION_MESSAGE);

长代码只是获取失败玩家的引用,并从他那里调用highestRankingCard()。 基本上我所做的就是调用 card

的 toString
public String toString()
{
    if(rank == 16)
        return "Black Joker";
    else if(rank == 17)
        return "Red Joker";
    else
    {
        String s = "";

        if(rank == 15)
        {
            s = s + "2";

            if(suit.equals("h"))
                s = s + " of hearts";
            else if(suit.equals("d"))
                s = s + " of diamonds";
            else if(suit.equals("c"))
                s = s + " of clubs";
            else if(suit.equals("s"))
                s = s + " of spades";

            return s;
        }
        else if(rank == 14)
        {
            s = s + "Ace";

            if(suit.equals("h"))
                s = s + " of hearts";
            else if(suit.equals("d"))
                s = s + " of diamonds";
            else if(suit.equals("c"))
                s = s + " of clubs";
            else if(suit.equals("s"))
                s = s + " of spades";

            return s;
        }

        if(suit.equals("h"))
            s = s + " of hearts";
        else if(suit.equals("d"))
            s = s + " of diamonds";
        else if(suit.equals("c"))
            s = s + " of clubs";
        else if(suit.equals("s"))
            s = s + " of spades";

        return s;
    }
}

最后添加的是我从用户那里得到的卡: 15 is the rank of deuce that's fine, but of diamonds? That is spades, but anyway I did another try and I get even a more joking sentence. The rank is missing! Is this even possible with the code above? Sorry if I am missing something.

注意:由于卡片是绘制的图像,如果它是带有文件名的东西,我会注意到的。刚做了检查,没问题

我认为问题不仅仅是排名没有被打印出来。您需要确保您的代码具有内聚性并最大限度地减少耦合。看起来 toString 方法做了很多实际上不应该做的工作,对象中的所有内容都应该尽可能只关注该对象实例中包含的信息,并且每个方法都应该专注于做一样东西。为什么不将卡片的名称和颜色存储在卡片中,这样就可以简单地执行

public String toString(){
    return this.colour + " " + this.name;
} 

而不是试图推断你是哪个卡片实例。 你就是卡片。你应该能够从你自己那里收集到这些信息。底线是良好的编程实践是好的,因为它们可以帮助很多事情,它们可以帮助您进行调试,更多方法 = 要遵循的堆栈跟踪更多,可能出现的问题范围更窄,并且它们有助于提高可读性。

抱歉,这可能不是您想听到的,但您可能需要进行一些重大重构才能解决问题。