Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop with Dice rolling program, previous roll and double check

Tags:

java

dice

A fairly trivial problem to most I am sure but I can't quite work out how I'm meant to get the previous dice integer to remain the same as the previous roll of die in the program. I think the code is fairly self explanatory and this is such a trivial program I'm kicking myself for not being able to get my head around it.

import java.util.Random;

public class Dice {

    public static void main(String[] args) {
        Random rand = new Random();
        int min = 1;
        int max = 6;
        int loop = 0;
        int diceRollOne = 0;
        int diceRollTwo = 0;
        int diceTotal = 0;
        int prevDiceTotal = 0;

        while (loop < 15000) {
            loop++;
            diceRollOne = rand.nextInt(max - min + 1) + min;
            diceRollTwo = rand.nextInt(max - min + 1) + min;
            diceTotal = diceRollOne + diceRollTwo;

            System.out.println("Dice Roll 1: " + diceRollOne);
            System.out.println("Dice Roll 2: " + diceRollTwo);
            System.out.println("Dice Total: " + diceTotal);
            System.out.println("previous total: " + prevDiceTotal);

            prevDiceTotal = diceTotal;

            if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
                System.out.println("After " + loop + " loops the");
                System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
                System.exit(0);
            }
        }
    }
}

The basic idea being 15,000 simulations. Roll two dice. If you roll a double quit. If you roll the same sum in the current roll as the sum of the previous roll then quit. I've tried debugging by printing out the previous dice total but it defaults to zero every time.

like image 296
Timothy Ford Avatar asked Apr 30 '26 17:04

Timothy Ford


2 Answers

You just want to move the prevDiceTotal = diceTotal; to after your if statement.

        if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
            System.out.println("After " + loop + " loops the");
            System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
            System.exit(0);
        }

        prevDiceTotal = diceTotal;
like image 143
greedybuddha Avatar answered May 03 '26 07:05

greedybuddha


You have the following:

prevDiceTotal = diceTotal;

if(diceRollOne == diceRollTwo || diceTotal == prevDiceTotal){

As it's written now it guarantees if-expression to be True.

Move the assignment after your if block.

like image 30
PM 77-1 Avatar answered May 03 '26 07:05

PM 77-1