Error: Getting "non-static variable ... cannot be referenced" when trying to fill and array with random numbers

Error: Getting "non-static variable ... cannot be referenced" when trying to fill and array with random numbers

我正在尝试将 30 个元素的数组转换为 30 个随机数的数组,但我一直在 "numbers[counter] = randomInt;" 上收到错误 "Non-static variable rand cannot be referenced in a static context" 我在这方面还很陌生,我四处寻找类似的问题和解决方案,但我发现的一切都不清楚。

public static void main(String[] args)
{
    final int length = 30;
    int numbers[] = new int[length];
    int randomInt;
    int counter;

    for(counter = 0; counter < numbers.length; counter++)
    {
        randomInt = 1 + rand.nextInt(100);
        numbers[counter] = randomInt;
        System.out.printf("Digit %d: %d \n", counter, numbers[counter]);
    }   
}  

}

您需要在使用前实例化一个名为 rand 的新 Random class 对象。

public static void main(String[] args)
{
    final int length = 30;
    int numbers[] = new int[length];
    int randomInt;
    int counter;
    Random rand = new Random();

    for(counter = 0; counter < numbers.length; counter++)
    {
        randomInt = 1 + rand.nextInt(100);
        numbers[counter] = randomInt;
        System.out.printf("Digit %d: %d \n", counter, numbers[counter]);
    }   
}