java 播放器类返回null 0 null [已关闭]

busg9geu  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(133)

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
3天前关闭。
Improve this question
我创建了一个播放器:Player player = new Player(hand, 5000, "Player_1");
当打印类时,它打印"null0null"
为什么不保存变量?谢谢!
玩家职业:

public class Player {
    private Hand hand; //hand with 5 cards
    private int chips; //chips left
    private String name; //name of player

    public Player (Hand hand, int chips, String name) {
        hand = this.hand;
        chips = this.chips;
        name = this.name;
    }

    public int getChips() {
        return chips;
    }

    public Hand getHand() {
        return hand;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return name + " " + chips + " " + hand;
    }
}
q8l4jmvw

q8l4jmvw1#

  • "...为什么不保存变量?..."*

在构造函数方法中,您可以反转赋值。

public Player (Hand hand, int chips, String name) {
    hand = this.hand;
    chips = this.chips;
    name = this.name;
}

它应该是,以下。

public Player (Hand hand, int chips, String name) {
    this.hand = hand;
    this.chips = chips;
    this.name = name;
}

在这种情况下,this 关键字用于区分示例变量和局部变量。

相关问题