如何计算数组中 15 个数字的出现次数?

How to count occurrences of 15 numbers that are in an array?

我是编写代码的新手。我需要制作一个程序,将 15 个数字读入一个介于 0-50 之间的数组,然后打印出现的次数。这是我目前所拥有的。

import java.util.Scanner;
public class Occurrence
{
   public static void main(String[] args)
  {
      Scanner scan = new Scanner(System.in);
      int [] nmberchck = new nmberchck[50];
      int[] numbs = new int[15];
      System.out.println("Enter 15 numbers that are between 0 and 50 ");
      System.out.println();
      numbs[0] = scan.nextInt();
      numbs[1] = scan.nextInt();
      numbs[2] = scan.nextInt();
      numbs[3] = scan.nextInt();
      numbs[4] = scan.nextInt();
      numbs[5] = scan.nextInt();
      numbs[6] = scan.nextInt();
      numbs[7] = scan.nextInt();
      numbs[8] = scan.nextInt();
      numbs[9] = scan.nextInt();
      numbs[10] = scan.nextInt();
      numbs[11] = scan.nextInt();
      numbs[12] = scan.nextInt();
      numbs[13] = scan.nextInt();
      numbs[14] = scan.nextInt();
      for (int nmb = 0; nmb < numbs.length; nmb++)

谢谢

更简单的版本:

public static void main(String[] args) {
        int[] nmberchck = new int[51];
        int[] numbs = new int[15];
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter 15 numbers that are between 0 and 50 ");
        System.out.println();
        for (int i = 0; i < 15; i++) {
            numbs[i] = sc.nextInt();
        }
        for (int i = 0; i < 15; i++) {
            if (!(numbs[i] < 0 || numbs[i] > 50))
                nmberchck[numbs[i]]++;
        }

        for (int i = 0; i < nmberchck.length; i++)
            if (nmberchck[i] > 0)
                System.out.println(i + " occured " + nmberchck[i]
                        + " times");
    }

更有趣的版本:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    HashMap<Integer, Integer> x = new HashMap<Integer, Integer>();
    ArrayList<Integer> m = new ArrayList<Integer>();
    for (int i = 0; i < 15; i++) {
        int tmp = sc.nextInt();
        if (!x.containsKey(tmp))
            x.put(tmp, 1);
        else
            x.put(tmp, x.get(tmp) + 1);
        if (!m.contains(tmp))
            m.add(tmp);
    }

    for (int i = 0; i < m.size(); i++)
        System.out.println(m.get(i) + " occured " + x.get(m.get(i)) + " times");

}

这将按递增顺序打印出每个数字出现的次数。希望这有帮助。

所以你必须打印输入的每个数字的出现次数?

我不知道你的老师有什么想法,但你已经有了一个名为 nmberchck 的 50 数组。你可以使用这个数组来计算每个数字出现的次数,因为数字在 0 到 50 之间。虽然实际上,如果你包括数字 0 和 50,你真的需要一个 51 的数组。

首先,每个数字出现 0 次。所以最初需要将 nmberchck 中的每个元素设置为 0。您可以使用循环来执行此操作。

接下来您必须接受 15 个数字作为输入,并使用 nmberchck 对每个数字进行计数。因为你做同样的事情 15 次,所以使用循环。

所以有两个循环,一个是初始化,一个是读入一个数然后计数。

这两个循环是嵌套的吗?要回答这个问题,请了解您重复了多少次。 首先将 nmberchck 元素初始化为 0:重复 51 次。 然后获取输入:重复 15 次。 总计:66 次重复。

当重复像这样添加时,那就是一个循环接着一个循环。

嵌套循环是一个循环套在另一个循环中,在这种情况下,重复次数会增加。

接下来要做的是打印结果。由于 nmberchck 包含您的结果,您将再次循环它。

当您尝试编写代码时,将问题的解决方案分解为简单的步骤。尝试量化并了解您自己是如何解决它的。你会如何手动解决这个问题?理解这一点后才能编写代码。

顺便说一句,这不是解决这个问题的最有效方法,但它是对数组、循环和索引的一个很好的介绍。大多数 nmberchck 元素将不会被使用,因为您只输入 15 个数字 - nmberchck 是一个稀疏填充的数组。