【发布时间】:2017-02-13 00:24:41
【问题描述】:
我正在尝试在大小为 6 的数组中计算 ints 的出现次数,包括 1 到 6 次。我想返回一个数组,其中包含 int 在每个索引中出现的次数,但是一个在索引零处。
示例:
输入:[3,2,1,4,5,1,3]
预期输出:[2,1,2,1,1,0]。
问题:
它输出[1,1,3,0,1,0],代码摘录如下。我怎样才能解决这个问题?我找不到哪里出错了。
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
}
return amt;
}
public int[] countNumOfEachScore(){
int[] scores = new int[6];
int[] counts = new int[6];
for (int i = 0; i < 6; i++){
scores[i] = dice[i].getValue();
}
for (int j = 0; j < 6; j++){
counts[j] = arrayCount(scores, j+1);
}
return counts;
}
dice[] 只是一个 Die 对象数组,它有一个 getValue() 方法,它返回一个介于 1 和 6 之间的 int,包括 1 和 6。 counts[] 是包含错误内容的 int 数组。
【问题讨论】:
-
为什么不使用 Collections.frequency() 来获取每个数组元素的计数
-
你的想法很慢...@mhasan