【发布时间】:2021-09-07 17:34:09
【问题描述】:
我正在处理一项硬件分配,该分配要求编写一个名为 count 的方法,该方法确定目标值在数组中出现的次数。例如,如果您的数组是 [2, 3, 3, 3, 4, 6, 7, 8, 8, 9],则值 8 出现两次,数字 4 出现一次。你应该知道该方法有两个参数和一个返回值。代码有效,但我遇到的问题是,当我打印语句“值 x[i] 出现计数(x,x[i])次”时,它重复相同的语句,而它应该只打印每个值的语句.我需要帮助来制作它,所以它只会打印该语句,只要该值与它之前的值不同,如果它与它之前的值相同,代码应该跳过并移动到数组中的下一个值,直到它打印所有内容。
import java.util.Arrays;
public class Q7 {
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
for (int i = 0; i < x.length; i++) {
System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
}
}
public static int count(int[] array, int target) {
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
counter++;
}
}
return counter;
}
}
Output:
[2, 3, 3, 3, 4, 6, 7, 8, 8, 9]
The value 2 appears 1 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 4 appears 1 times.
The value 6 appears 1 times.
The value 7 appears 1 times.
The value 8 appears 2 times.
The value 8 appears 2 times.
The value 9 appears 1 times.
【问题讨论】:
-
除非您被告知该数组将被排序,否则我建议您弄清楚如何对未排序的数组执行此操作。此外,排序不是必需的。