AbbenGabben
AbbenGabben

Reputation: 107

Java: While Loop and array incrementing

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

Upvotes: 2

Views: 147

Answers (3)

yeputons
yeputons

Reputation: 9238

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

Upvotes: 2

Ali Hashemi
Ali Hashemi

Reputation: 3368

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.

Upvotes: 1

Mateusz
Mateusz

Reputation: 3048

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;

Upvotes: 4

Related Questions