java - 我的嵌套 for 循环有问题吗?对数组的值进行计数和递增

标签 java arrays for-loop random nested

因此,我生成了 0 到 9 范围内的 100 个数字。我将这 100 个数字存储在一个名为“array”的数组中。然后我有一个名为“count”的数组。它有 10 个元素,我想检查以下内容:对于“array”中的每个元素,如果它等于 0-9,则 count[0-9] 递增 1,count[0] = 数字 0 出现的次数和所以 count[1] = 1, count[2] = 2...。我只是不断得到大约 20k 个数字的输出,我想?每个元素的总和?,不知道为什么。我想知道我的 for 循环是否有什么重大问题?

import java.util.*;

class RandomInt {
    public static void main(String[] args) {
        int size = 100;
        int max = 10;
        int[] array = new int[size];
        int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
        int loop = 0;

        Random generator = new Random();


        for (int i = 0; i < size; i++) {
            array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
            System.out.print(array[i]);
            for (int x = 0; x < size; x++) {// loop through 10 elements in count
                for(int j = 0; j < 10; j++){ //loop through 100 elements in array
                    if (array[x] == j) {// loop through each 100 elements of array[x] and if element array[x] = value
                        count[j] += 1; // then count[x] = x + 1
                        System.out.print(count[j]);
                    }
                }
            }
        }

        System.out.println("0 appears " + count[0] + " times.");
    }
}

最佳答案

您的登录是完美的,我发现您犯的唯一错误是括号......!

使用第一个循环生成数字,然后使用不同的 for 循环计算出现的次数。

这是您的代码的修改版本,它生成 10 个数字并计算单个数字的出现次数......

public class RandomInt {
 public static void main(String[] args) {
    int size = 10;
    int max = 10;
    int[] array = new int[size];
    int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
    int loop = 0;

    Random generator = new Random();


    for (int i = 0; i < size; i++) 
    {
        array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
        System.out.print(array[i]+" ");
    }

    for (int x = 0; x < size; x++) 
    {// loop through 10 elements in count
            for(int j = 0; j < 10; j++)
            { //loop through 100 elements in array
                if (array[x] == j) 
                {// loop through each 100 elements of array[x] and if element array[x] = value
                    count[j] += 1; // then count[x] = x + 1
                    //System.out.print(count[j]);
                }
            }

    }

    System.out.println("3 appears " + count[3] + " times.");
}

}

关于java - 我的嵌套 for 循环有问题吗?对数组的值进行计数和递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24248499/

相关文章:

java - Jsonpath 总是返回空列表

java - 使用 Spring bean 的惰性对象构建器

java - 使用 onClickListener 将数据发送到下一个 Activity 的一些问题

c - C 中输入整数的特定位数计数

java - 数组的随机改组

python - Python 中的嵌套 for 循环涉及 2 个文件

java - 将逗号分隔的字符串作为 sql "IN"子句的输入

java - Math.random 到一个数组中,然后将数组打印成 10 行,每行 10

c++ - 将 R 代码转换为 C++ 以进行 Rcpp 实现

linux - 多次重复文本