1

I used the Random class to generate the number from 1 to 20. Then, I added it into a ArrayList, but the error message showed "Cannot make a static reference to the non-static method nextInt(int) from the type Random". How could I do? Below is my code.

import java.util.ArrayList;
import java.util.Random;

public class ComputerChoose {

static ArrayList<Integer> computer_number = new ArrayList<>();

public static ArrayList<Integer> getTheNumber() {

    for(int times=0; times<5; times++)
    {
        computer_number.add(Random.nextInt(20) + 1);
    }

    return computer_number;
    }
}
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
user8654396
  • 35
  • 1
  • 2
  • 6
  • 4
    Because `nextInt` is an instance method, not a static one. You need to create an instance of `Random`, i.e. `Random r = new Random();` – bcsb1001 Nov 29 '17 at 17:29
  • 1
    Your problem has nothing to do with putting the result in an array. You could have isolated the problem by first trying the simpler task of creating a simple variable containing a random number. Stripping down problems to the simplest form makes for the best SO questions -- and often in the process you solve it for yourself. – slim Nov 29 '17 at 17:34
  • Also ArrayList can have duplicates, then either check if number already exists in the list and do not put it if so, or use one of the `java.util.Set` implementations. `Set` has no duplicates. – Vadim Nov 29 '17 at 17:36

2 Answers2

3

nextInt is not a static method. You have to create an instance of Random, and call it as an instance method:

import java.util.ArrayList;
import java.util.Random;

public class ComputerChoose {

    static ArrayList<Integer> computer_number = new ArrayList<>();

    public static ArrayList<Integer> getTheNumber() {
        Random random = new Random();

        for(int times=0; times<5; times++) {
            computer_number.add(random.nextInt(20) + 1);
        }

        return computer_number;
    }
}

See also the JavaDocs for java.util.Random.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0
public static ArrayList<Integer> getTheNumber() {
    Random rand = new Random(); // create instance of Random class
    for(int times=0; times<5; times++)
    {
        computer_number.add(rand.nextInt(20) + 1);
    }
    return computer_number;
}
Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22