Dice Roll Histogram - java

I have a class question that I cannot seem to understand the logic for.
Modify the program below to print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like * that number of times, as shown below.
Histogram showing total number of dice rolls for each possible value.
Dice roll histogram:
2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
I do not understand what in the world this histogram is displaying. Its driving me insane and I cannot move forward with my logic if I do not understand what I am doing. I know this question has been asked before but it looks like they all have a specific number of dice roles they are going off of. I am not given a number and this is what is throwing me off. I know this is really a stupid question. But can anyone possibly explain to me what they mean by "Histogram showing total number of dice rolls for each possible value" what is defining this possible value? I am at a total loss... Any help is appreciated. Here is the code I have written so far.
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
int numOnes = 0; // Tracks number of 1's found
int numTwos = 0; // Tracks number of 2's found
int numThrees = 0; // Tracks number of 3's found
int numFours = 0; // Tracks number of 4's found
int numFives = 0; // Tracks number of 5's found
int numSixes = 0; // Tracks number of 6's found
int numSevens = 0; // Tracks number of 7's found
int numEights = 0; // Tracks number of 8's found
int numNines = 0; // Tracks number of 9's found
int numTens = 0; // Tracks number of 10's found
int numElevens = 0; // Tracks number of 11's found
int numTwelves = 0; // Tracks number of 12's found
int die1 = 0; // Dice values
int die2 = 0; // Dice values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// Count number of sixes and sevens
if (rollTotal == 1) {
numOnes = numOnes + 1;
}
if (rollTotal == 2) {
numTwos = numTwos + 1;
}
if (rollTotal == 3) {
numThrees = numThrees + 1;
}
if (rollTotal == 4) {
numFours = numFours + 1;
}
if (rollTotal == 5) {
numFives = numFives + 1;
}
if (rollTotal == 6) {
numSixes = numSixes + 1;
}
if (rollTotal == 7) {
numSevens = numSevens + 1;
}
if (rollTotal == 8) {
numEights = numEights + 1;
}
if (rollTotal == 9) {
numNines = numNines + 1;
}
if (rollTotal == 10) {
numTens = numTens + 1;
}
if (rollTotal == 11) {
numElevens = numElevens + 1;
}
else if (rollTotal == 12) {
numTwelves = numTwelves + 1;
}
System.out.println("Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Prints a histogram of the number of dice rolls
System.out.println("\nDice roll histogram:");
System.out.println("1's: " + numOnes);
System.out.println("2's: " + numTwos);
System.out.println("3's: " + numThrees);
System.out.println("4's: " + numFours);
System.out.println("5's: " + numFives);
System.out.println("6's: " + numSixes);
System.out.println("7's: " + numSevens);
System.out.println("8's: " + numEights);
System.out.println("9's: " + numNines);
System.out.println("10's: " + numTens);
System.out.println("11's: " + numElevens);
System.out.println("12's: " + numTwelves);
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
You can see where I entered the entry for histograms. I basically thought that I needed to edit my value given from the integers such as "numOnes" to asterisk but now I'm not certain... any help is appreciated!
EDITED CODE -
System.out.println("\nDice roll histogram:");
System.out.print("2's: ");
for(i = 0; i < numTwos; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("3's: ");
for (i = 0; i < numThrees; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("4's: " );
for (i = 0; i < numFours; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("5's: ");
for (i = 0; i < numFives; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("6's: ");
for (i = 0; i < numSixes; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("7's: ");
for (i = 0; i < numSevens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("8's: ");
for (i = 0; i < numEights; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("9's: ");
for (i = 0; i < numNines; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("10's: ");
for (i = 0; i < numTens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("11's: ");
for (i = 0; i < numElevens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("12's: ");
for (i = 0; i < numTwelves; i++);{
System.out.print("*");
}
System.out.println("");
}
OUTPUTS -
Enter number of rolls:
5
Roll 1 is 8 (2+6)
Roll 2 is 9 (6+3)
Roll 3 is 9 (5+4)
Roll 4 is 6 (4+2)
Roll 5 is 9 (6+3)
Dice roll histogram:
2's:
3's: *
4's: *
5's: *
6's: *
7's: *
8's: *
9's: *
10's: *
11's: *
12's: *
I can enter a larger number of rolls and I will get an asterisk for the 2's and it will increase like I need but it will not increase the rest of the numbers and they all only get one asterisk. What is keeping my code from properly increasing the amount of *'s? Iv been fighting with this for hours :/

"I do not understand what in the world this histogram is displaying."
Well, as you said:
"Histogram showing total number of dice rolls for each possible value"
The histogram:
2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
is a record of the rolls of a pair of six sided dice. The possible values of totaling a pair of dice range from 2 to 12. If you rolled them 100 times they might give these results.
This histogram shows that the value 6 was most frequently rolled (19 times) and 4 the least frequently rolled (3 times). If you counted up every * you'd know how many times the dice have been rolled.
You may think that a histogram must look like this:
But turn that sideways:
and imagine that the blue bars are *'s, the 100 - 150 label is a 2, and the 150 - 200 label is a 3, well then it starts to look like your histogram.
Either form is a histogram. They let you compare quantities (how many) of things that fall in different categories (kinds) of things.
A graphic chart is difficult to output from a program that is text based so instead it's asking you to display what is basicly ascii art:
If this was in a text file, and not program output, this could also be considered a form of tally. You can easily add new *'s as you receive new data. It's the same trick as this:
Hope that makes more sense.
SPOILER ALERT: If that helped and you'd like to take a crack at modifying the program yourself read no further. Otherwise...
This
System.out.println("\nDice roll histogram:");
System.out.println(" 1's: " + nManyStars(numOnes));
System.out.println(" 2's: " + nManyStars(numTwos));
System.out.println(" 3's: " + nManyStars(numThrees));
System.out.println(" 4's: " + nManyStars(numFours));
System.out.println(" 5's: " + nManyStars(numFives));
System.out.println(" 6's: " + nManyStars(numSixes));
System.out.println(" 7's: " + nManyStars(numSevens));
System.out.println(" 8's: " + nManyStars(numEights));
System.out.println(" 9's: " + nManyStars(numNines));
System.out.println("10's: " + nManyStars(numTens));
System.out.println("11's: " + nManyStars(numElevens));
System.out.println("12's: " + nManyStars(numTwelves));
and this
static String nManyStarsOld(int n) {
String result = "";
for (int i = 0; i < n; i++) {
result += "*";
}
return result;
}
should, if dropped in the right places, get your program to stop printing what it prints now which is this:
Enter number of rolls:
20
Roll 1 is 5 (2+3)
Roll 2 is 10 (4+6)
Roll 3 is 7 (5+2)
Roll 4 is 7 (5+2)
Roll 5 is 5 (1+4)
Roll 6 is 11 (6+5)
Roll 7 is 8 (3+5)
Roll 8 is 8 (2+6)
Roll 9 is 7 (1+6)
Roll 10 is 8 (3+5)
Roll 11 is 12 (6+6)
Roll 12 is 6 (2+4)
Roll 13 is 8 (6+2)
Roll 14 is 8 (4+4)
Roll 15 is 7 (1+6)
Roll 16 is 4 (2+2)
Roll 17 is 6 (5+1)
Roll 18 is 7 (6+1)
Roll 19 is 6 (1+5)
Roll 20 is 5 (1+4)
Dice roll histogram:
1's: 0
2's: 0
3's: 0
4's: 1
5's: 3
6's: 3
7's: 5
8's: 5
9's: 0
10's: 1
11's: 1
12's: 1
And instead, get it to print this:
Dice roll histogram:
1's:
2's:
3's:
4's: *
5's: ***
6's: ***
7's: *****
8's: *****
9's:
10's: *
11's: *
12's: *
Next time you post a question please include the current output along with the expected output.
If you feel like being a smarty pants there is actually a one line version of nManyStars():
static String nManyStars(int n) {
return new String(new char[n]).replace("\0", "*");
}
Inspired by this: https://stackoverflow.com/a/4903603/1493294
Also, if you have at least Java 11 you can trade in nManyStars(n) for "*".repeat(n)
Hope it helps

Iv got it all working. Thank you #CandiedOrange and #MadProgrammer for the help and guidance! Found that my histogram code was messed up with my for statements having a ; in an incorrect spot causing my for statement to not apply the * based on its process of running through the for statement and it was just printing a * as a normal print function. All is well. Thanks for all the help!

Related

Dice simulation in java

I'm trying to simulate rolling a die 100 times, and printing the results of how many 1/2/3/4/5/6 i landed. Here's my code thus far: I'm trying to use a while loop for my assignment, and i need to use (Math.random( )*6 + 1) to generate numbers.
public class RollingDice {
public static void main(String args[]) {
int count = 0; // number of times die was rolled
int count1s = 0; // number of times 1 was rolled
int count2s = 0; // number of times 2 was rolled
int count3s = 0;
int count4s = 0;
int count5s = 0;
int count6s = 0;
while (count < 100) {
count1s = (int) (Math.random( )*6 + 1);
count2s = (int) (Math.random( )*6 + 1);
count3s = (int) (Math.random( )*6 + 1);
count4s = (int) (Math.random( )*6 + 1);
count5s = (int) (Math.random( )*6 + 1);
count6s = (int) (Math.random( )*6 + 1);
count++;
}
System.out.println("Number of times the die was rolled: "+ count);
System.out.println("Number of times 1 was rolled: " + count1s);
System.out.println("Number of times 2 was rolled: " + count2s);
System.out.println("Number of times 3 was rolled: " + count3s);
System.out.println("Number of times 4 was rolled: " + count4s);
System.out.println("Number of times 5 was rolled: " + count5s);
System.out.println("Number of times 6 was rolled: " + count6s);
}
}
My code currently prints:
Number of times the die was rolled: 100
Number of times 1 was rolled: 3
Number of times 2 was rolled: 1
Number of times 3 was rolled: 5
Number of times 4 was rolled: 2
Number of times 5 was rolled: 4
Number of times 6 was rolled: 4
As you can see, its rolling 100 times, but its only saving the results of 1 roll, not 100, How do I fix this?
On each iteration of your while loop, you are reassigning the value of count1s, count2s, and the others. Instead what you should do is you should "roll the dice" and then see what value it is, and increment the proper variable.
while (count < 100) {
int diceRoll = (int) (Math.random() * 6 + 1);
if (diceRoll == 1)
count1s++;
else if (diceRoll == 2)
count2s++;
// ... you get the idea
count++;
}
And as a fun sidenote, using Java 8 there is a significantly easier, and more cool way to do this.
Stream.generate(() -> (int) (Math.random() * 6 + 1))
.limit(100L)
.collect(Collectors.groupingBy(num -> num,
Collectors.counting()))
.forEach((num, count) -> System.out.println("number of times " + num + " was rolled: " + count));
Each iteration you are replacing the previous roll's data.You can rewrite the logic as
// initialization
while(count < 100){
int currentRoll = (int) (Math.random() * 6 + 1);
if(currentRoll == 1)
count1s++;
// Same logic for all occurances
}
Because your logic is incorrect.
Inside while loop, you assigned appearance time of each roll with value of dice.
=> Counter of each always < 7.
Also, each time your call Math.random() will give you new value => Should call it once each roll.
In this case, use switch - case statement will be correct.
while (count < 100) {
int num = (int) (Math.random( )*6 + 1);
switch(num) {
case 1:
count1s++;
break;
case 2:
count2s++;
break;
case 3:
count3s++;
break;
case 4:
count4s++;
break;
case 5:
count5s++;
break;
case 6:
count6s++;
break;
}
count++;
}

Java: Array asterisk printing for values

I am trying to print asterisks based on the number of times a dices side is rolled (all through an array). I am coming across an issue with the printing of the dice side (i) before the asterisks. Also, I'm getting two zeroes out of nowhere and don't know where they're coming from.
I'd appreciate the help.
My code:
public class Histogram {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numRoles = 100;
int[] amountRoles = new int[7]; // amountRoles Holds the array
for (int i = 1; i < 7; i++)
amountRoles[i] = 0; // Set 0
{
for (int i = 0; i < numRoles; i++)
{
int die1 = (int)(Math.random()*6+1);
amountRoles[die1]++; // Increments
}
System.out.println("The die was rolled " + numRoles + " times, its six value's counts are:");
for (int i = 1; i < 7; i++)
{
System.out.print("Side " + i + " was rolled " + amountRoles[i]+ " times out of " + numRoles + ".");
// Prints each sides value (i) alongside with how many times it was rolled (amountRoles[i]).
System.out.println(); // Formatting Line
}
}
for (int i = 0; i < amountRoles.length; i++) // Iterates through amountRoles
{
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
System.out.print("" + "*");
}
System.out.println(i + " " + amountRoles[i]);
}
}
}
My output:
The die was rolled 100 times, its six value's counts are:
Side 1 was rolled 11 times out of 100.
Side 2 was rolled 19 times out of 100.
Side 3 was rolled 19 times out of 100.
Side 4 was rolled 17 times out of 100.
Side 5 was rolled 16 times out of 100.
Side 6 was rolled 18 times out of 100.
0 0 (Where are these zeroes coming from?)
***********1 11
*******************2 19
*******************3 19
*****************4 17
****************5 16
******************6 18
An example output I am aiming for:
[1] ******************* 19
[2] ************ 12
[3] ********************* 21
[4] ******************** 20
[5] ************* 13
[6] *************** 15
You're starting at zero?
also for the mid line
System.out.println(); // Formatting Line
the above can be removed and just add ln to the previous output.
I'd also use a variable to keep count of the string and then append it.
for (int i = 1; i < amountRoles.length; i++) // Iterates through amountRoles
{
String asterCount = "";
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
asterCount += ("*");
}
System.out.println("[" +i +"]"+ " "+ asterCount + " "+ amountRoles[i]);
}
Only answering your question an no other problems I see with the code, you are getting the 0 0 from int i = 0. Change this to int i = 1 and no more 0 0!
To get your values to print the way you need, you just need to simple move what you want to print before the * above the loop. In this case [i], and move the amount each roll was below the * loop. Code is below. This should fix your stated problems.
for (int i = 1; i < amountRoles.length; i++) // Iterates through amountRoles
{
System.out.print("[" + i + "]");
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
System.out.print("" + "*");
}
System.out.println(" " + amountRoles[i]);
}

Creating a single die roll program in Java, but rather than rolling 300 times, it is rolling 320 times

I have been trying to find where the error is in this code for some time now and I just can't figure it out. The program is rolling a 6 sided die 300 times, and then outputting the number of time each number is rolled. But for some reason, rather than rolling it 300 times, it's rolling 320 times. I don't see anything wrong with the for-loop so I'm really at a loss here.
public static void dieRoll(){
int[] roll = new int [300];
int[] count = new int[] {1,2,3,4,5,6};
for(int i = 1; i<300; i++){
roll[i] = (int) Math.ceil( (int) (Math.random()*6)+1 );
// roll[i] = (int) Math.ceil(roll[i]);
// System.out.println(roll[i]);
if(roll[i]==1){
count[0]++;
}
else if(roll[i]==2){
count[1]++;
}
else if(roll[i]==3){
count[2]++;
}
else if(roll[i]==4){
count[3]++;
}
else if(roll[i]==5){
count[4]++;
}
else if(roll[i]==6){
count[5]++;
}
// System.out.println(roll[i]);
}//i loop
System.out.println("The die landed on 1 " + count[0] + " times.");
System.out.println("The die landed on 2 " + count[1] + " times.");
System.out.println("The die landed on 3 " + count[2] + " times.");
System.out.println("The die landed on 4 " + count[3] + " times.");
System.out.println("The die landed on 5 " + count[4] + " times.");
System.out.println("The die landed on 6 " + count[5] + " times.");
System.out.println("The die was rolled this many times: " + (count[0]+count[1]+count[2]+count[3]+count[4]+count[5]));
}//dieRoll()
If someone could just please point me out to where the error might be manifesting itself, that would be awesome. Thank you.
You initialised your counts like this:
int[] count = new int[] {1,2,3,4,5,6};
Now, 1 + 2 + 3 + 4 + 5 + 6 is equal to 21. Your loop goes from 1 to 299, which is 299 iterations. And of course, 299 + 21 is 320.
You should initialise your array to all zeros.
Finally, your code can be simplified:
for( int i = 0; i < 300; i++ )
{
roll[i] = (int) Math.ceil( (int) (Math.random()*6)+1 );
count[roll[i] - 1]++;
}

How to reset the for loop with out loosing the info entered for the previous "batter"?

My problem is when the console prints the results; the program seems to be adding all of the results and I can't seem to figure out how to reset each one with out loosing it. I'm pretty sure the problem lies on the for loop but I still have no idea on how to fix it.
Here is the full code:
import java.util.*;
import java.text.NumberFormat;
public class BattingAverageApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
double successfulRuns = 0;
double totalBases = 0;
int atbatt = 0;
String message = " ";
AtBat bat = new AtBat();
System.out.print("Number of batters: ");
int batters = sc.nextInt();
System.out.println();
bat.setPlayers(batters);
int[] atbat = new int[batters];
double[][] calculate = new double[batters][2];
outerLoop:
for(int a = 0; a < batters; a++)
{
atbat[a] = Validator.getInt(sc, "Enter the number of times at bat for player "
+ (a+1) + ": ", 0, 11);
System.out.println();
atbatt = atbat[a];
double[] results = new double[atbatt];
System.out.println("0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run");
for(int i = 0; i < atbatt; i++)
{
results[i] = 0;
results[i] = Validator.getInt(sc, "Results for at-bat " + i + ": ", -1, 5);
bat.setResult(results[i]);
if (results[i] > 0)
successfulRuns++;
totalBases += results[i];
}
System.out.println();
}
for(int a = 0; a < batters; a++)
{
calculate[a][0] = successfulRuns / (double)atbatt;
calculate[a][1] = totalBases / (double)atbatt;
NumberFormat number = NumberFormat.getNumberInstance();
number.setMinimumFractionDigits(3);
message = "Batting average: " + number.format(calculate[a][0]) + "\t"
+ "Slugging percent: " + number.format(calculate[a][1]);
System.out.println(message);
}
System.out.println();
}
}
Here is what the console prints out, when I select one player:
Number of batters: 1
Enter the number of times at bat for player 1: 3
0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run
Results for at-bat 0: 0
Results for at-bat 1: 4
Results for at-bat 2: 0
Batting average: 0.333 Slugging percent: 1.333
Press any key to continue . . .
And here is what it prints out when I select more than one player:
Number of batters: 2
Enter the number of times at bat for player 1: 3
0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run
Results for at-bat 0: 0
Results for at-bat 1: 4
Results for at-bat 2: 0
Enter the number of times at bat for player 2: 2
0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run
Results for at-bat 0: 0
Results for at-bat 1: 1
Batting average: 1.000 Slugging percent: 2.500
Batting average: 1.000 Slugging percent: 2.500
Press any key to continue . . .
It is probably because of those lines:
calculate[a][0] = successfulRuns / (double)atbatt;
calculate[a][1] = totalBases / (double)atbatt;
You cast only the denominator. But the nominator is an integer as well. You have to cast all the variables to double. Change the lines with these:
calculate[a][0] = (double)((double)successfulRuns / (double)atbatt);
calculate[a][1] = (double)((double)totalBases / (double)atbatt);
It would appear that you are not clearing the old values with each loop iteration to your setResult method. I can't say for certain since you have not posted the code for your AtBat class, but I would take a look at that method.
Ok I figured it out. I just had to move my equation for the if (results[a] > 0)
successfulRuns++;
totalBases += results[a]; outside of the inner for loop.
its working perfect now. Thanks to those who tried to assist.
for(int a = 0; a < batters; a++)
{
atbat[a] = Validator.getInt(sc, "Enter the number of times at bat for player "
+ (a+1) + ": ", 0, 11);
System.out.println();
atbatt = atbat[a];
double[] results = new double[atbatt];
System.out.println("0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run");
for(int i = 0; i < atbatt; i++)
{
results[i] = 0;
results[i] = Validator.getInt(sc, "Results for at-bat " + i + ": ", -1, 5);
bat.setResult(results[i]);
}
if (results[a] > 0)
successfulRuns++;
totalBases += results[a];
System.out.println();
calculate[a][0] = successfulRuns / (double)atbatt;
calculate[a][1] = totalBases / (double)atbatt;
}
for(int a = 0; a < batters; a++)
{
NumberFormat number = NumberFormat.getNumberInstance();
number.setMinimumFractionDigits(3);
message = "Batting average: " + number.format(calculate[a][0]) + "\t"
+ "Slugging percent: " + number.format(calculate[a][1]);
System.out.println(message);
}

Die Simulator nested loop issue

import java.util.Scanner;
public class DiceSimulator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many dice do you want to roll: ");
int amountOfDie = input.nextInt();
System.out.println("");
// declare diceArray
Die[] diceArray = new Die[amountOfDie];
// create a new Die for each reference
int maxRoll = 0;
for (int i = 0; i < diceArray.length; i++) {
System.out.print("How many sides on die number " + (i + 1) + "" + ": ");
int numSides = input.nextInt();
diceArray[i] = new Die(numSides);
int minRoll = amountOfDie;
maxRoll += numSides;
}
int minRoll = amountOfDie;
// int[] sumArray = new int[maxRoll + 1];//to store sum
System.out.println("");
System.out.print("How many times do you want to roll: ");
int numRol = input.nextInt();
System.out.println("\nResults");
// ******** right here is where I'm having the issue.
for (int i = 0; i < numRol; i++) {
diceArray[i].roll();
// System.out.println(diceArray[i]);
int sum = 0;
for (int f = 0; f < numRol; f++) {
sum += diceArray[f].roll();
int[] sumArray = new int[maxRoll + 1];
sumArray[sum]++;
System.out.print("\t" + sum);
}
}
// for(Die d: diceArray){
// System.out.println(d);
// }
}
}
See commented line in code: // ******** right here is where I'm having the issue.
The for loop should spit out the sum of the rolls.
It just isn't spitting out the right values. I'm just curious where I went wrong? The program should ask the user how many rolls. This would go into the first for loop and the second would roll the dice that many times.
I think what you're trying to do is roll these dice a said number of times, keeping track of how often each total is reached, so you can print them at the end. Try this:
int[] sumArray = new int[maxRoll];
for (int i = 0; i < numRol; i++) {
int sum = 0;
for (Die d : diceArray) {
int roll = d.roll();
sum += roll;
System.out.print("\t" + roll);
}
System.out.println("\t:\t" + sum);
sumArray[sum-1]++;
}
for (int i = 0; i < sumArray.length; i++){
System.out.printf("%d: %d Rolls\n", i+1, sumArray[i]);
}
You can see it working here. Your most basic mistakes were:
Declare your sum array before you start calculating sums.
In the inner loop, iterate over your dice, one at a time, rolling, adding to the sum, and printing.
Print your sum and increment your count after the dice have been rolled.
If you roll two six sided dice 10 times with this algorithm, you'll get:
Results
4 3 : 7
5 5 : 10
2 2 : 4
6 5 : 11
1 1 : 2
6 5 : 11
6 5 : 11
1 2 : 3
2 1 : 3
3 5 : 8
1: 0 Rolls
2: 1 Rolls
3: 2 Rolls
4: 1 Rolls
5: 0 Rolls
6: 0 Rolls
7: 1 Rolls
8: 1 Rolls
9: 0 Rolls
10: 1 Rolls
11: 3 Rolls
12: 0 Rolls
You have a line that looks like this:
diceArray[i].roll();
The problem is that diceArray is only large as the number of dice you have. But you are trying to use it with an index of the number of rolls. This could cause an ArrayOutOfBoundsException.

Categories