gpt4 book ai didi

java - 如何让Java中的计数器持久化?

转载 作者:行者123 更新时间:2023-11-30 07:48:08 25 4
gpt4 key购买 nike

我正在制作一个骰子游戏,通过掷 7 或 11(一对骰子)来得分。游戏会记录投注和得分。满足条件时,当前分数应加至投注金额的3倍。然而,分数仅在满足条件的第一个实例中改变,然后在任何其他掷骰尝试中保持不变。我尝试将 getter 和 setter 设置为静态,但这不起作用。我该怎么做才能使我的计数器正常工作?

程序:

    public Game() {

final Dice throwDice = new Dice();

//Roll Dice
rollDice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

throwDice.PairOfDice();
diceResult.setText("You rolled: " + throwDice.getDie1() +
" + " + throwDice.getDie2() +
" = " + throwDice.getTotal());
currentScore.setText("Score: $" + throwDice.getScore());
if(throwDice.getTotal() == 7 || throwDice.getTotal() == 11) {
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
currentScore.setText("Score: $" + throwDice.getScore());
}
}
});

最佳答案

你的骰子声明:

Dice throwDice = new Dice();

位于 actionPerformed() 中,这意味着每次调用该函数时都会创建它。

将声明移动到Game中,即。让它成为游戏的一个属性,你应该没问题。

您可以安全地将 Dice::scoreDice::getScore()Dice:setScore(int) 设置为非静态。

更新:鉴于仍然存在问题,也许尝试替换:

 throwDice.setScore(Integer.parseInt(input.getText()) * 3);

与:

 throwDice.setScore(throwDice.getScore() + (3 + throwDice.getBet()));

关于java - 如何让Java中的计数器持久化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33663976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com