Loops as counters - Java

0 Shawn Slinger · April 29, 2015
I am trying to build on a simple program i created to simulate rolling a die. I need to count the number of rolls it takes for the die to turn up sixes three times straight. I basically want to understand what are the best methods to select to get this done. 

Here is my code.

import java.util.Random;

public class rollingDie {

    private static int count;
    private static int result;
    
     

    //Simulates rolling a six sided die 
    static int roll() {
        Random r = new Random();
        result =r.nextInt(6) + 1;
        return result;
    }

    //main method prints result of roll() to System.out
    public static void main(String[] args) {

        rollingDie x = new rollingDie();
        System.out.println("The die shows " + x.roll());
        

    }
}

Post a Reply

Replies

Oldest  Newest  Rating
+2 Jake Scaife · April 29, 2015
Use an incrementing variable. Set the variable to 0, if a 6 is rolled or whatever, add 1 to the variable. If anything else is rolled reset the variable to 0. If the variable is rolled 3 times in a row then the variable will get to 3, can use an if statement during each loop to test that.
0 Nicholas Eason · April 29, 2015
Here's a list of pseudo-code that could work for this situation:

while hasHappened is false
roll
increment roll counter variable
if number is 6, increment 6 counter variable, else,  6 counter variable is 0

if 6 counter variable is 3, hasHappened is true
0 steven kitchener · April 30, 2015
Hi shawn,

The best way to do this, as suggested above is to use a couple of variables and a while loop. 

int total = 0;
int sixes = 0;
Random rand = new Random();
do{
int num = rand.nextInt(6)+1;
if(num == 6){
sixes++;
}else{
sixes = 0;
}
total++;

}while(sixes != 3);

System.out.println(total);

This loop will keep running until three sixes are found in a row. what it does is check to see if num is equal to six and if so increment the variable sixes by one otherwise reset it back to zero. The total variable keeps track of how many numbers in total has been checked. The loop will exit when sixes == 0 and then you will get a print out of how long it took.

In maths terms you should get around 216 every time, (1/6 *1/6*1/6 = 1/216) .... if you run the program multiple times and take an average then youll get close to that number.

Hope this helps,

Steven
0 Shawn Slinger · May 1, 2015
Best thanks guys! I'm preparing for exams and I want to get in all the practice i need. 
  • 1

Java / Android Development

107,253 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator