Ja-oon Solo Ja-oon Solo - 4 months ago 27
Java Question

java - Random inside while loop causes infinite loop with all same numbers

On the Programming By Doing website I'm stuck on the DoubleDice exercise. It's supposed to run a while loop until you come up with the same value for each dice (doubles - 3 and 3, 4 and 4, etc.)

I've input what I think to be the correct code, but I get this infinite loop that prints out the exact same "randoms" every time through the while loop.

I've pondered this for about a day and decided to give it to SO.

Thanks.

import java.util.Random;

public class diceDoubles {

public static void main(String[] args){

Random dice = new Random();

int roll1 = 1 + dice.nextInt(6);
int roll2 = 1 + dice.nextInt(6);

System.out.println("HERE COMES THE DICE!\n");

while(roll1 != roll2) {

System.out.println("Die 1: " + roll1);
System.out.println("Die 2: " + roll2);
System.out.println("The total is " + (roll1 + roll2) + "\n");
}
}
}

Answer

You need to add "variables roll1 and roll12 update code" to while loop, like this:

while(roll1 != roll2) {

    roll1 = 1 + dice.nextInt(6);
    roll2 = 1 + dice.nextInt(6);

    System.out.println("Die 1: " + roll1);
    System.out.println("Die 2: " + roll2);
    System.out.println("The total is " + (roll1 + roll2) + "\n");
}
Comments