我正在参加 Java 入门类(class),但我被一项作业困住了。目标是使用单维数组编写一个程序,该数组读取 7 个整数,然后显示输入的每个值重复出现的次数(即,如果输入数字 12 两次,则输出行之一是“数字 12 出现 2 次。 ”)
我已经写了其中的一些内容,但我一直不知道如何计算每个数组元素出现的次数。我有一个想法,我需要一个方法和第二个数组,但我遇到了困难:
public class NumOfOccurrIn7 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Declare scanner and array
Scanner A = new Scanner(System.in);
int counter[] = new int[7];
System.out.print("Please enter 7 numbers: ");
//Populate initial array
for(int t = 0; t < 7; t++) {
counter[t] = A.nextInt();
}
//Process # of reoccurences and print results
for(int t=0; t<7; t++) {
}
for(int t=0; t<7; t++) {
System.out.print("Number " + counter[t] + " occurs " + x +
" times./n");
}
}
public static int CountOccurrance(int counter[]) {
}
}
感谢您的反馈!
最佳答案
如果数字 12 出现两次,您不希望输出打印两次,因此首先检查该数字是否已被处理。您可以通过迭代之前 t
之前的数组元素来完成此操作。 ,如果其中之一与当前数字相同,则不会打印任何内容。
接下来检查数组的其余部分并计算当前数字出现的次数,然后打印消息。
// Process # of reoccurences and print results
for (int i = 0; i < 7; i++) {
boolean print = true;
int count = 0;
for (int j = 0; j < 7; j++) {
if (counter[j] == counter[i]) {
if (j < i) {
print = false;
break;
}
count++;
}
}
if (print) {
System.out.println("Number " + counter[i] +
" occurs " + count + " times.");
}
}
关于Java - 读入7个整数,计算重复出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60471198/