我正在尝试模拟骰子游戏实验。目标是找到平均卷数,以获得相同的骰子值,以显示所需的连续卷数。
我的程序询问用户用户想要运行程序的次数。所以它会运行循环,然后在得到答案后停止,然后显示它所花费的数量。然后它将重复用户指定的次数。
我想从每个实验中取出totalThrows
并将每个totalThrows
加在一起,然后除以我的变量turns
,以获得它所需的平均投掷量。
我在获取所有totalThrows
的总和时遇到了一些麻烦。我只能得到最后一个totalThrow
。如果你们中的任何人能就如何解决这个问题提出一些建议,我将不胜感激。我认为数组可以提供帮助,但我还没有在课堂上学过数组。
这是我的代码。
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
int value, turns=0, nSides, rollLength; //declare variables
int totalThrows=0, roll=0, count=0,finish=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
System.out.println("\n");
do
{
//Countinue loop until count = rollLength
while(count!=rollLength){
roll = randomNumber.nextInt(nSides)+1;
totalThrows++; //will increment after every roll
//When roll comes up as a watched value I want to increment count by one
if(roll==value){
count++; //This should stop until count is my rollLength
}
else if (roll!=value){ //When an unwanted roll comes up start over
count=0;
}
}
//finish counts how many times the experiment was successful
if (count==rollLength){
finish++;
}
System.out.println("\n");
//Display totalThrows it took until rollLength variable occurs
System.out.println("Your total rolls is: "+ totalThrows);
} while(finish!=turns); //This will repeat the experiment
}
}
答案 0 :(得分:0)
简单地在顶部声明另一个变量:
int averageThrows = 0;
每次循环结束时添加到此值:
do {
// ...
averageThrows += totalThrows;
} while( finish != turns );
然后除以转数:
averageThrows /= turns;
那应该为你做。