Java 滚动2个六边形骰子1000次,意外结果
当模拟滚动2个骰子1000次并显示结果时,它会不断返回意外值。我的计划是:Java 滚动2个六边形骰子1000次,意外结果,java,arrays,random,dice,Java,Arrays,Random,Dice,当模拟滚动2个骰子1000次并显示结果时,它会不断返回意外值。我的计划是: 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
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");
}
}
}
这是错误的,因为每个值的总和超过1000,两个骰子的滚动次数。有什么解决办法吗?问题在于每次滚动后都没有重置计数变量 消除
count++
,只需执行arr[j]++
编辑
如中所述,循环是不必要的,因为您只需执行
arr[sumOfRolls]++
您没有在每次滚动后重置计数如果没有循环,那么arr[sumOfRolls]++
不会更好吗?@Andreas,的确如此
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