这是我的方法
private static void methodCount(int[] array) {
Arrays.sort(array);
for(int i = 0;i < array.length;i++) {
int num1 = array[i];
int counter = 0;
for(int j = 0;j < array.length;j++) {
int num2 = array[j];
if(num1 == num2) {
counter++;
i++;
}
}
System.out.println("Number " + num1 + " is counted " + counter + " times!");
}
}
我无法弄清楚为什么输出会发生变化,例如:
int[] array = {2, 4, 2, 5, 6, 7, 7, 4, 9, 2, 1, 3, 8};
methodCount(array);
输出
Number 1 is counted 1 times!
Number 2 is counted 3 times!
Number 4 is counted 2 times!
Number 7 is counted 2 times!
Number 9 is counted 1 times!
对于这个数组
int[] array = {2, 4, 2, 5, 6, 7, 7, 4, 9};
methodCount(array);
输出
Number 2 is counted 2 times!
Number 4 is counted 2 times!
Number 7 is counted 2 times!
删除最后四个数字:2,1,3,8。
我不知道Arrays.sort(数组)是不是必需的。
谢谢!
答案 0 :(得分:2)
问题是比较if(num1 == num2)会执行自我比较。这意味着,在其中一个迭代中,num1和num2将是数组中完全相同的元素。对于这种情况,增加了一个&#39; i&#39;不是必需的。
另一种解决方案如下:
private static void methodCount(int[] array) {
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
int num1 = array[i];
int counter = 1;
for (int j = i + 1; j < array.length; j++) {
int num2 = array[j];
if (num1 == num2) {
counter++;
i++;
}
}
System.out.println("Number " + num1 + " is counted " + counter + " times!");
}
}
答案 1 :(得分:0)
在您的第二个for
循环中,在if(num1 == num2)
语句中:
您应该删除i++;
即使您第一次尝试此阵列int[] array = {2, 4, 2, 5, 6, 7, 7, 4, 9, 2, 1, 3, 8};
methodCount(array);
你不是在计算所有数字。 (6?8?)。