Search code examples
arraysrandomstaticsyntax-errornon-static

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

}


Solution

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