Java Reference
In-Depth Information
for(String go : goes) {
die1 = 1 + diceValues.nextInt(6);
// Number from 1
to 6
die2 = 1 + diceValues.nextInt(6);
// Number from 1
to 6
System.out.println(go + " 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;
}
}
Dice.java
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...
How It Works
You use a random number generator that you create using the default constructor, so it is seeded with
the current time and produces a different sequence of values each time the program is run. You simulate
throwing the dice in the for loop. For each throw you need a random number between 1 and 6 to be gen-
erated for each die. The easiest way to produce this is to add 1 to the value returned by the nextInt()
method when you pass 6 as the argument. If you want to make a meal of it, you could obtain the same
result by using the following statement:
die1 = 1 + abs(diceValues.nextInt())%6; // Number from 1 to 6
Remember that the pseudo-random integer values that you get from the version of the nextInt()
method you are using here is uniformly distributed across the whole range of possible values for type
int , positive and negative. That's why you need to use the abs() method from the Math class here to
make sure you end up with a positive die value. The remainder after dividing the value resulting from
abs(diceValues.nextInt()) by 6 is between 0 and 5. Adding 1 to this produces the result you want.
Search WWH ::




Custom Search