Hello everyone, I am sure the dice game has been discussed numerous times on here. I am hoping to get some feedback on my take of the dice game. This was a homework assignment and I have completed the requirements. I am just wanting to see where I could have done better and where I could have saved time and effort. I appreciate any feedback that I receive.
The task asked to create a program to ask the user how many times they would like to roll the dice. Then using a random number generator roll the dice that many times and print out the values of each roll. After that create a histogram of the number of times a certain value was rolled(2-12).
int input, rollTotal, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter how many times you would like to roll "
+ "the dice: ");
input = sc.nextInt();
//These are the arrays used to store the values generated by the loop
// instructions.
int [] die1 = new int[input];
int [] die2 = new int[input];
int [] rollHist = new int[11];
Random r = new Random();
/* This block of code generates the random numbers for die1 and die2
* and stores the values of each roll in the die1 and die2 arrays.
* It then prints to the screen what each die represents for each roll
* of the dice.
*/
for (int i = 0; i < die1.length; i++)
{
die1[i] = r.nextInt(6) + 1;
}
for (int j = 0; j < die2.length; j++)
{
die2[j] = r.nextInt(6) + 1;
}
for(int d = 0; d < input; d++)
{
System.out.print(count += 1);
System.out.println(" : I rolled a " + die1[d] + " and a " + die2[d]);
rollTotal = die1[d] + die2[d]; // This creates a total of the sum
if (rollTotal == 2) // for each roll of the dice. With the if
{
rollHist[0] += 1; // statements it calculates how many times
}
if (rollTotal == 3) // a certain value is produced by a roll of the
{
rollHist[1] += 1; // dice.
}
if (rollTotal == 4)
{
rollHist[2] += 1;
}
if (rollTotal == 5)
{
rollHist[3] += 1;
}
if (rollTotal == 6)
{
rollHist[4] += 1;
}
if (rollTotal == 7)
{
rollHist[5] += 1;
}
if (rollTotal == 8)
{
rollHist[6] += 1;
}
if (rollTotal == 9)
{
rollHist[7] += 1;
}
if (rollTotal == 10)
{
rollHist[8] += 1;
}
if (rollTotal == 11)
{
rollHist[9] += 1;
}
if (rollTotal == 12)
{
rollHist[10] += 1;
}
}
/* This section calculates and displays a histogram for the value of
* each roll of the dice.
*/
System.out.println();
System.out.println("Histogram of rolls:");
/* In this final for loop the string variable histogram is created to
* change the total count for each value of the dice roll from 2-12 into
* that many asterisk symbols. If there is no count for a certain value
* then there are no asterisk printed to the screen.
*/
count = 1;
for (int k = 0; k < rollHist.length; k++)
{
System.out.print(count += 1);
String histogram;
histogram = new String(new char[rollHist[k]]).replace('\0', '*');
System.out.println(" : " + histogram);
}
}
}