java - 使用数组计算出现次数 - Java

标签 java arrays

我不知道如何将 0-9 之间随机生成的 100 个数字与数组值(也是 0-9 之间)进行比较,然后打印结果。对我放轻松,我是编码新手,我知道我很烂。我觉得我已经达到了 75%。我知道有一些方法可以减少一些代码的冗余,但我似乎很难使用这些技术。

这是我目前所拥有的:

public static void main(String[] args) {
    double randomNum = 0;
    for (int i = 0; i < 100; i++) {
        randomNum = Math.random() * 10;

    int count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0;
    int count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0;
    int [] arrayNums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    for (double j = 0; j <arrayNums.length; j++){
        if (arrayNums[0] == randomNum) {
            count0++;
        }
        else if (arrayNums[1] == randomNum){
            count1++;
        }
        else if (arrayNums[2] == randomNum){
            count2++;
        }else if (arrayNums[3] == randomNum){
            count3++;
        }else if (arrayNums[4] == randomNum){
            count4++;
        }else if (arrayNums[5] == randomNum){
            count5++;
        }else if (arrayNums[6] == randomNum){
            count6++;
        }else if (arrayNums[7] == randomNum){
            count7++;
        }else if (arrayNums[8] == randomNum){
            count8++;
        }
        else{
            count9++;
        }

    }
    System.out.print("Occurrences of 0: " + count0);
    System.out.print("\nOccurrences of 1: " + count1);
    System.out.print("\nOccurrences of 2: " + count2);
    System.out.print("\nOccurrences of 3: " + count3);
    System.out.print("\nOccurrences of 4: " + count4);
    System.out.print("\nOccurrences of 5: " + count5);
    System.out.print("\nOccurrences of 6: " + count6);
    System.out.print("\nOccurrences of 7: " + count7);
    System.out.print("\nOccurrences of 8: " + count8);
    System.out.print("\nOccurrences of 9: " + count9);
    }
}

感谢任何帮助。

最佳答案

  • 使用 HashMap 作为计数器比单独使用一个更优雅 每个项目的变量。
  • 使用 Random.nextInt(10) 生成 0 到 9(含)之间的随机数。

        Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
        Random rand = new Random();
        for (int i = 0; i < 100; i++) {
            int randomNum = rand.nextInt(10);
            Integer currentCount = counter.get(randomNum);
            if (null == currentCount) {
                counter.put(randomNum, 1);
            } else {
                counter.put(randomNum, currentCount+1);
            }
        }
        for (Integer key : counter.keySet()) {
            System.out.println(key + " -> " + counter.get(key));
        }
    

示例输出

0 -> 12
1 -> 10
2 -> 9
3 -> 6
4 -> 8
5 -> 9
6 -> 11
7 -> 12
8 -> 14
9 -> 9

关于java - 使用数组计算出现次数 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28470173/

相关文章:

c++ - 在 C++ 中获取 Vector 的一部分,例如指向 C 数组中间的指针

java - 插件管理没有父pom的版本

java - 在 Java 中打印 JTable 和其他文本字段

java - 如何使用列表随机化 netbeans 中的数组?

c# - 为什么创建新数组会抛出 OutOfMemoryException?

php - 将平面数组转换为分层的多维数组

arrays - 在 Perl DBI 中使用数组插入 1 行和很多列

java - 如何使用 System.currentTimeMillis() 以秒为单位测量时间跨度?

java - 读取文件并将数据存储到多个数组时出错