简体   繁体   中英

Error: Getting “non-static variable … cannot be referenced” when trying to fill and array with random numbers

I'm trying to convert an array of 30 elements into an array of 30 random numbers but I keep receiving the error "Non-static variable rand cannot be referenced in a static context" on the "numbers[counter] = randomInt;" I'm fairly new at this and I've looked around for similar questions and solutions but everything I found was unclear.

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]);
    }   
}  

}

You need to instantiate a new Random class object named rand before using it.

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]);
    }   
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM