Search code examples
javajframecounterjlabeldice

How to make a counter persist in Java?


I'm making a dice game that scores points based on rolling a 7 or 11(pair of dice). The game keep track of the bets and score. The current score should be added to 3 times the bet amount if the the condition is met. However the score only changes the in the first instance the condition is met, then remain the same through any other roll attempts. I tried to set my getters and setters to be static but that didn't work. What can I do to make my counter work properly?

Program:

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

Solution

  • In your question you say:

    The current score should be added to 3 times the bet amount

    You are not adding to the current score. You are only setting the score to the 3 times the bet amount every time. So the value will not change (unless, of course, you change the bet amount).

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

    Instead you need to add it to the current score:

     throwDice.setScore(throwDice.getScore() + Integer.parseInt(input.getText()) * 3)