首页 > 解决方案 > Java - 读入 7 个整数,计算重复次数

问题描述

我正在学习 Java 入门课程,但我被困在作业中。目标是使用一维数组编写一个程序,该数组读取 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[]) {

    }

}

感谢您的反馈意见!

标签: javaarraysmethods

解决方案


如果数字 12 出现两次,您不希望输出打印两次,因此首先检查该数字是否已被处理。您可以通过遍历数组元素before 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.");
    }
}

推荐阅读