如何让一个计数器持续 Java?
How to make a counter persist in Java?
我正在制作一个基于掷出 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::score
、Dice::getScore()
和 Dice:setScore(int)
成为非静态的。
更新:如果仍然存在问题,也许可以尝试替换:
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
与:
throwDice.setScore(throwDice.getScore() + (3 + throwDice.getBet()));
你需要搬家
Dice throwdice = new Dice`
上代码,这样就不会每次进入actionperformed时都调用
在你的问题中你说:
The current score should be added to 3 times the bet amount
您没有添加到当前分数。您每次都只是将分数设置为下注金额的 3 倍。所以价值不会改变(当然,除非你改变投注金额)。
throwDice.setScore(Integer.parseInt(input.getText()) * 3)
相反,您需要将其添加到当前分数:
throwDice.setScore(throwDice.getScore() + Integer.parseInt(input.getText()) * 3)
我正在制作一个基于掷出 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::score
、Dice::getScore()
和 Dice:setScore(int)
成为非静态的。
更新:如果仍然存在问题,也许可以尝试替换:
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
与:
throwDice.setScore(throwDice.getScore() + (3 + throwDice.getBet()));
你需要搬家
Dice throwdice = new Dice`
上代码,这样就不会每次进入actionperformed时都调用
在你的问题中你说:
The current score should be added to 3 times the bet amount
您没有添加到当前分数。您每次都只是将分数设置为下注金额的 3 倍。所以价值不会改变(当然,除非你改变投注金额)。
throwDice.setScore(Integer.parseInt(input.getText()) * 3)
相反,您需要将其添加到当前分数:
throwDice.setScore(throwDice.getScore() + Integer.parseInt(input.getText()) * 3)