家庭作业。骰子游戏。我有一个代表五次骰子的数组。考虑:
diceRoll[] = {6,3,3,4,5}
。我想创建一个 SECOND 数组,其中包含 diceRoll[]
中包含的从 1 到 6 的值计数(例如,occurrence[] = {0,0,2,1, 1,1}
对于上面的 diceRoll[]
。)但我担心我会迷失在嵌套循环中,并且似乎无法弄清楚我应该返回哪个值。 occurrence[]
是一个全局变量,其目的是该数组将包含六个值...个数(在索引 [0] 处)、两个数(在 [1] 处)、三个数(在[2])等。
到目前为止:
for(i=1;i<7;i++) /* die values 1 - 6
{
for(j=0;j<diceRoll.length;j++) /* number of dice
{
if (diceRoll[j] == i) /* increment occurences when die[j] equals 1, then 2, etc.
occurence = occurence + 1;
}
}
return occurence;
}
但是,我无法让occurrence=occurrence+1 起作用。 二元运算符的操作数类型错误
是我最常见的错误。我怀疑我需要在一个或两个 for 循环之外增加出现
,但我迷失了。
指导?或者也许是单行简单的方法来做到这一点? d
最佳答案
我必须执行此操作的最简单方法是按顺序创建第二个数组,以便 出现次数[0] = 1 的出现次数[1] = 2 的次数,依此类推。那么这就变成了1个循环方法。
//method to return number of occurrences of the numbers in diceRolls
int[] countOccurrences(int[] diceRolls) {
int occurrence[] = new int[6]; //to hold the counts
for(int i = 0; i < diceRolls.length; i++) { //Loop over the dice rolls array
int value = diceRolls[i]; //Get the value of the next roll
occurence[value]++; //Increment the value in the count array this is equivalent to occurrence[value] = occurrence[value] + 1;
//occurrence[diceRolls[i]]++; I broke this into two lines for explanation purposes
}
return occurrence; //return the counts
}
编辑:
然后要获取任何特定值的计数,请使用occurrence[value-1]
关于java - 计算数组中某个值的实例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9779894/