如何仅显示 java 中用户输入的数字?

How to show only occurrences of numbers user input in java?

我是编程新手,正在尝试解决这个问题,但不知道我做错了什么。

该程序应该在输入 0 之前接收用户输入,然后打印出用户输入数字出现的信息 - 这就是我的问题。

我写的程序显示了所有数字的出现(最多可以输入的最大数字),而不仅仅是用户写的那些。

我的代码:

package numbers;

import java.util.Scanner;

public class Numbers {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int[] occurences = new int[11];

        int num = scan.nextInt();
        while (num > 0 && num <= 11) {
            occurences[num]++;
            num = scan.nextInt();
        }
        for (int i = 0; i < 11; i++) {
            System.out.print("Value: " + i + " Occurences: " + occurences[i] + " ");
        }
    }
}

使用 if 语句只打印出现次数大于 0 的数字。

旁注:

  1. 不需要数组值初始化:
for (int i = 0; i < 11; i++) {
   occurences[i] = 0;
}

每个索引处的值已经为 0,请检查此 question

  1. while循环条件,意义不大
while (num > 0 && num <= 11) {
   occurences[num]++;
   num = scan.nextInt();
}

数组大小为 11,这意味着索引范围从 0 到 10(含)。由于您允许输入 11,因此您将得到 ArrayIndexOutOfBoundsException.

你可以利用地图。

    Map<Integer, Integer> occ = new HashMap<>();

    int num = scan.nextInt();
    while (num > 0 && num <= 11) {
        occ.put(num, occ.getOrDefault(num, 0)+1);
        num = scan.nextInt();
    }

    for(int i : occ.keySet()){
        System.out.print("Value: " + i + " Occurences: " + occ.get(i) + " ");
    }