When simulating rolling 2 dice 1000 times and displaying the result, it keeps returning unexpected values. My program is:
import java.util.*;
public class Prob1 {
private int sides; //Amount of sides on die
private int sumOfRolls;
private int[] arr; //Array that holds the count of each sum of the rolls
private int count; //Temporarily holds value of sum of rolls before passing to array
public Prob1() { //Default constructor, sets sides to 6
sides = 6;
sumOfRolls = 0;
count =0;
arr = new int[(sides*2)+1];
}
public void roll() { //Method that rolls the 2 dice
for(int i=0;i<1000;i++) { //Repeats 1000 times
int roll1 = (int) (Math.random()*sides)+1; //Rolls 1 die
int roll2 = (int) (Math.random()*sides)+1; //Rolls other die
sumOfRolls = roll1+roll2; //Sums both rolls
for(int j=2;j<(sides*2)+1;j++) { //Goes through all the possible values of sums of roll
if(sumOfRolls==j) { //Checks if sum of rolls is equal to the value presented by the for loop
count++; //Adds 1 to count of value of sum of roll
arr[j]=count; //Adds that value to array
}
}
}
System.out.println("Roll: " + sides + "-sided dice"); //Displays what kind of dice
}
public void frequency() { //Frequency table
System.out.println("\n\n\nRoll Total Frequency");
System.out.println("---------------------");
for(int i=2; i<(sides*2)+1; i++) { //Displays each value of array
System.out.print(i + " " + arr[i] + "\n");
}
}
}
When both the roll and frequency methods are called, this is the result:
Roll: 6-sided dice
Roll Total Frequency
---------------------
2 952
3 995
4 976
5 989
6 991
7 999
8 1000
9 998
10 992
11 994
12 997
This is erroneous, as the sum of each value exceeds 1000, the number of times the two dice are rolled. Is there any fix to this?
Aucun commentaire:
Enregistrer un commentaire