-1

i want t0 set a variable to let agent random get a number between 1-10(later use the number to filter people), but how could i set the formula for random variable? i use Random.next Int(1)+ 5; but error says :Cannot make a static reference to the non-static method next Int(int) from the type Random. could you please help me? really a emergency

  • Please read [mre]. – Connor Low May 21 '21 at 20:23
  • Does this answer your question? [Cannot make a static reference to the non-static method fxn(int) from the type Two](https://stackoverflow.com/questions/11491750/cannot-make-a-static-reference-to-the-non-static-method-fxnint-from-the-type-t) – SiKing May 21 '21 at 21:11

1 Answers1

0

You need a Random object.

Random rand = new Random();//Create random object
int randomInt = rand.nextInt(10)+1;

This is central to java in general. Non-static methods are attached to an object rather than a class, which is why you need to create an object to use them.

Dejke
  • 168
  • 1
  • 9
  • thanks so much for replying!! but error shows Random cannot be resolved to a variable. is there something i miss? – conut Co May 21 '21 at 10:29
  • You need `import java.util.Random;` at the top of the program, after package – Dejke May 21 '21 at 11:27
  • it has import java.util.Random, i checked the java source, after package – conut Co May 21 '21 at 11:51
  • I think you must have mixed up `rand` and `Random` somewhere. `rand` is the name of the `Random` object. Can you try copying exactly from the answer to see if it works? The resulting number will be in `randomInt`. – Dejke May 21 '21 at 11:58
  • x=new Random(); int randomInt = x.nextInt(11); i type like this, and error says Cannot invoke nextInt(int) on the primitive type int. cannot convert from Random to int. – conut Co May 21 '21 at 13:07