Assignment:
Roll 5 dice and print out the total of the five dice. Repeat this 20 times and
then print the total.
Here is sample output:
5 dice: 5, 6, 1, 1, 2 total roll is 15
5 dice: 5, 5, 1, 4, 2 total roll is 17
...
total of all 20 rolls is 355
------------------
Help for rolling 5 dice assignment
Steps - I recommend compiling and running after every step:
First, figure out how to get 1 die to roll and print its value. (To do that,
just copy the code below into your program.)
Then, make it 5 dice rolling one after the other. (I prefer you to use a loop
that runs 5 times for this.)
Then, add those 5 dice up and print the total.
Then, add an outer loop around the rolling dice to roll them 20 times.
Then, add a running total of those 20 rolls.
------------------
Here is some help with rolling a single die, which uses Math.random(). Math.random's
job is to give you a number between 0 and 1 -
that is what it knows how to do, so you just ask it for the random number and
put the response into a double variable.
(If you put the response into an integer, it would truncate the decimal and
give you zero.)
If you just wanted to roll 1 die, you would do the following:
/** oneDie - generates one throw of one die
* uses a random number generator to do that
**/
public class oneDie
{
public static void main (String [] args)
{
double x; // holds the random number we will generate
int diceValue; // holds the value of the dice that we calculate from the random
number
x = Math.random(); // generates a number between 0 and 1
x = x *6; // multiplies that number times 6 so the number will be
from 0 to 5
diceValue = (int) x; // convert it to integer to chop off the decimal portion
diceValue = diceValue +1; // with dice, we want 1-6, not 0-5, so we add 1
System.out.print ("Die: " + diceValue);
}
}