Monday, January 09, 2012

How To Simulate A Dice Roll In Java Code

How To Simulate a Dice Roll in Java
Like my previous simulation ( How To Simulate A Coin Toss ) our dice must be able to output a specific number of values at random. In the case of the dice, we will need six (6) different outputs from our rollDice method, 1,2,3,4,5,6.

Utilizing the Math class built into Java, you can call its "random" method like so...

public int rollDice(){
   //this will be our method where we can put our code 
   //(methods are the same thing as functions)
   double number = Math.random();

Now, what does the random function do?
The function returns a double (decimal) number value from .0000000 to .9999999. Because we know the range of values we are getting from Math.random() are only about 1 to about 0 randomly, we can break 0 to 1 into 6 parts!

To do this take the number, 1.00 (the theoretical highest possible value of Math.random method) and divide it by 6:   1.00/6  =  0.1666666

The six sections can be: 0.1666666*1; 0.1666666*2; 0.1666666*3; 0.1666666*4; 0.1666666*5; 0.1666666*6.

public int rollDice(){
    double number = Math.random();
        System.out.println("It landed on 1!");
        return 1;
    } else  if(number<0.1666666*2){
        System.out.println("It landed on 2!");
        return 2;
    } else if(number<0.1666666*3){
        System.out.println("It landed on 3!");
        return 3;
    } else if(number<0.1666666*4){
        System.out.println("It landed on 4!");
         return 4;
    } else if(number<0.1666666*5){
         System.out.println("It landed on 5!");
         return 5;
    } else {
        System.out.println("It landed on 6!");
        return 6;

The System.out.println lines are used to inform you, the programmer of what was rolled. The returned integer can be used to make the value available to other parts of your java project.

To test out the method: simply place rollDice(); in your main method.

If you enjoyed this post then you will love 20+ Java Math.random() Manipulations!

No comments: