2

I want the program to keep incrementing the innings for each iteration of the loop. When I run the program it's doing that, however it's showing me incorrect values.

For example: You rolled...4 Your total for this innings so far is 6

The second line should be showing, "... so far is 4"

This is the code that I have at the moment:

import java.util.Random;
import javax.swing.*;

public class shortSix {

    public static void main(String[] args) {
        diceGame();
}//ENDS MAIN
    public static void diceGame()
    {
        final int[] innings = new int[1];
        innings[0] = 0;

        Random dice = new Random();
        int diceRoll = dice.nextInt(6) + 1;

        while (diceRoll != 5)
        {
            System.out.println("You rolled..." + diceRoll);
            diceRoll = dice.nextInt(6) + 1;
            innings[0] =+ diceRoll;
            System.out.println("Your total for this innings so far is " + innings[0]);

            String userDeclare = JOptionPane.showInputDialog(null, "Do you wish to declare?");
            if (userDeclare.equals("yes"))
            {
                System.exit(0);
            }

        }
    }//ENDS diceGame
}//ENDS class shortSix
3
  • why is innings defined final? Commented Nov 23, 2013 at 14:08
  • I'm supposed to use a final variable to store values for this question Commented Nov 23, 2013 at 14:09
  • What is the purpose of =+ in innings[0] =+ diceRoll? Commented Nov 23, 2013 at 14:17

3 Answers 3

4

The problem is that you aren't updating the array record after the first roll. You've got int diceRoll = ..., then you assign random value to the variable again and add the score after the second roll. The first result is ignored. All you have to do is change

diceRoll = dice.nextInt(6) + 1;
innings[0] =+ diceRoll;

to

innings[0] =+ diceRoll;
diceRoll = dice.nextInt(6) + 1;
Sign up to request clarification or add additional context in comments.

1 Comment

I would have marked this as the accepted answer, however I have to wait for another 7 mins. I changed the order around and modified the =+ to +=
2

There are two problems:

  1. =+ instead of += before the second println
  2. Order of operations is strange. You first print the current value, then update it and only then increases counter and prints summary. Probably you wanna move diceRoll = dice... after the second println

1 Comment

Ahh that makes sense. I've changed it around now and it's working fine.
1

You call

diceRoll = dice.nextInt(6) + 1;

before printing

 System.out.println("Your total for this innings so far is " + innings[0]);

which causes making a new random number, and it is the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.