Jerry Woods
Jerry Woods

Reputation: 15

Why doesnt this while loop stop after roll1 and roll2?

I've created a simple dice roll program. But the while loop will not stop when roll1 and roll2 are equal. And the total is not adding up. The programs runs infinite times, I have to stop it. Please help.

Output:

Roll #1: 1
Roll #2: 2
Total is : 3
Roll #1: 4
Roll #2: 1
Total is : 3
Roll #1: 4
Roll #2: 4
Total is : 3
Roll #1: 2
Roll #2: 5
Total is : 3
Roll #1: 4
Roll #2: 4
Total is : 3
Roll #1: 0
Roll #2: 2
Total is : 3
Roll #1: 4
Roll #2: 3
Total is : 3

Source Code:

import java.util.Scanner;
import java.util.Random;

public class App1
{
    public static void main( String[] args )
    {
        Random r = new Random();

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

        System.out.println("Heres comes the dice!");
        System.out.println();


        while ( roll1 != roll2 )
        {
            System.out.println("Roll #1: "  + roll1);
            System.out.println("Roll #2: "  + roll2);
            System.out.println("Total is : " + total );

        }
        System.out.println("Roll #1: "  + roll1);
        System.out.println("Roll #2: "  + roll2);
        System.out.println("Total is : " + total );


    }
 }

Upvotes: 1

Views: 99

Answers (2)

fabian
fabian

Reputation: 82491

You want to roll until the dice rolls are the same, which means:

  1. Random values need to be created inside the loop. Otherwise either the loop doesn't get executed at all or the loop is an infinite loop.
  2. Using a do-while loop you get nicer code.
Random r = new Random();

System.out.println("Heres comes the dice!");
System.out.println();
int roll1, roll2;
do
{
    roll1 = 1+ r.nextInt(6);
    roll2 = 1+ r.nextInt(6);
    int total = roll1 + roll2;
    System.out.println("Roll #1: "  + roll1);
    System.out.println("Roll #2: "  + roll2);
    System.out.println("Total is : " + total );
} while (roll1 != roll2);

Upvotes: 1

Jordi Castilla
Jordi Castilla

Reputation: 27003

Because inside while loop you don't get new values:

while ( roll1 != roll2 )
{
    System.out.println("Roll #1: "  + roll1);
    System.out.println("Roll #2: "  + roll2);
    System.out.println("Total is : " + total );

    roll1 = 1+ r.nextInt(6);
    roll2 = 1+ r.nextInt(6);
    total = roll1 + roll2;
}

First time you enter in the while loop roll1 and roll2 has a random value, but if you don't change this values with the new lines I added, so you will loop always into the same values you had.

About values of roll1 and roll2 changing, that does not have sense for me, in my computer your code result is:

Launch1

Total is : 7
Roll #1: 1
Roll #2: 6
Total is : 7
Roll #1: 1
Roll #2: 6
Total is : 7
Roll #1: 1
Roll #2: 6
Total is : 7

Launch2

Total is : 8
Roll #1: 5
Roll #2: 3
Total is : 8
Roll #1: 5
Roll #2: 3
Total is : 8
Roll #1: 5
Roll #2: 3
Total is : 8

Upvotes: 3

Related Questions