Java Reference
In-Depth Information
We can give the Random class an outing with a simple program that simulates throwing a pair of dice.
We'll assume you get six throws to try to get a double six.
Try It Out - Using Random Objects
Here's the program:
import java.util.Random;
import java.io.IOException;
public class Dice {
public static void main(String[] args) {
System.out.println("You have six throws of a pair of dice.\n" +
"The objective is to get a double six. Here goes...\n");
Random diceValues = new Random(); // Random number generator
String[] theThrow = {"First ", "Second ", "Third ",
"Fourth ", "Fifth ", "Sixth "};
int die1 = 0; // First die value
int die2 = 0; // Second die value
for(int i = 0; i < 6; i++) {
die1 = 1 + diceValues.nextInt(6); // Number from 1 to 6
die2 = 1 + diceValues.nextInt(6); // Number from 1 to 6
System.out.println(theThrow[i] + "throw: " + die1 + ", " + die2);
if(die1 + die2 == 12) { // Is it double 6?
System.out.println(" You win!!"); // Yes !!!
return;
}
}
System.out.println("Sorry, you lost...");
return;
}
}
If you compile this program you should get output that looks something like this:
You have six throws of a pair of dice.
The objective is to get a double six. Here goes...
First throw: 3, 2
Second throw: 1, 1
Third throw: 1, 2
Fourth throw: 5, 3
Fifth throw: 2, 2
Sixth throw: 6, 4
Sorry, you lost...
Search WWH ::




Custom Search