Zak
Zak

Reputation: 43

Dice Rolling loop

I am trying to make a method with java that includes the simulation of rolling three dice, and it counts how many times the three six-sided dice must be rolled until the values showing are all different. I tried to create it while using a while loop but it doesn't seem to even run although there aren't any compiler errors. Here's the code I have so far:

public class Rollin {
    public static void diceGenerator() {
        int numOfRolls = 0; //starts at zero for the number of rolls
        int x = ((int)(Math.random() * 6 +1)); //simulation of three dice
        int y = ((int)(Math.random() * 6 +1));
        int z = ((int)(Math.random() * 6 +1));
        while(!(x != y && y != z && x != z)) { // to check if the dice have any similar numbers
            numOfRolls++; // counting the number of rolls
        }
        System.out.println(numOfRolls); //prints the number of rolls
    }
}

Upvotes: 1

Views: 5413

Answers (3)

Weston
Weston

Reputation: 1451

Well you don't have a main method. You need to add a main method to your Rollin class (assuming the Rollin class is the only class you're compiling/running) and call diceGenerator from inside of it.

public class Rollin
{
  public static void main (String[] args)
  {
      diceGenerator();
  }

  public static void diceGenerator()
  {
  int numOfRolls = 0; //starts at zero for the number of rolls
  int x = ((int)(Math.random() * 6 +1)); //simulation of three dice
  int y = ((int)(Math.random() * 6 +1));
  int z = ((int)(Math.random() * 6 +1));
  while(!(x != y && y != z && x != z))// to check if the dice have any similar numbers
  {
        numOfRolls++; // counting the number of rolls
  }
  System.out.println(numOfRolls); //prints the number of rolls 
  } 
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

You forgot to re-roll in your loop. Also, I'd use a do-while and Random.nextInt(int) and apply De Morgan's laws to your test. Something like

Random rand = new Random();
int numOfRolls = 0; //starts at zero for the number of rolls
int x;
int y;
int z;
do {
  numOfRolls++;
  x = rand.nextInt(6) + 1;
  y = rand.nextInt(6) + 1;
  z = rand.nextInt(6) + 1;
} while (x == y || y == z || x == z);

Upvotes: 2

Connorelsea
Connorelsea

Reputation: 2438

You do not have a main method. For simplicity's sake, the main method can be explained as a static method, not associated with any objects, that is the first thing to be fired when the Java program is run. It works similarly to any other method in your program, meaning that you can code as you'd like inside of it.

Fire your method from within a main method such as the following:

public static void main(String[] args) {
    diceGenerator();
}

Also, your code isn't in any kind of loop, so the dice rolling will only execute once.

Upvotes: 0

Related Questions