Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random integer between min and max in Java?

Tags:

java

random

What method returns a random int between a min and max? Or does no such method exist?

What I'm looking for is something like this:

NAMEOFMETHOD (min, max)  

(where min and max are ints), that returns something like this:

8 

(randomly)

If such a method does exist could you please link to the relevant documentation with your answer.

Thanks.


UPDATE

Attempting to implement the full solution and I get the following error message:

class TestR {     public static void main (String[]arg)      {            Random random = new Random() ;         int randomNumber = random.nextInt(5) + 2;         System.out.println (randomNumber) ;      }  }  

I'm still getting the same errors from the compiler:

TestR.java:5: cannot find symbol symbol  : class Random location: class TestR         Random random = new Random() ;         ^ TestR.java:5: cannot find symbol symbol  : class Random location: class TestR         Random random = new Random() ;                             ^ TestR.java:6: operator + cannot be applied to Random.nextInt,int         int randomNumber = random.nextInt(5) + 2;                                          ^ TestR.java:6: incompatible types found   : <nulltype> required: int         int randomNumber = random.nextInt(5) + 2;                                              ^ 4 errors 


What's going wrong here?

like image 892
David Avatar asked Mar 14 '10 22:03

David


People also ask

How do you generate a random number with MIN MAX?

The built-in function Math. random() creates a random value from 0 to 1 (not including 1 ). Write the function random(min, max) to generate a random floating-point number from min to max (not including max ).

How do you generate a random integer value in Java?

In order to generate Random Integer Numbers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.


2 Answers

Construct a Random object at application startup:

Random random = new Random(); 

Then use Random.nextInt(int):

int randomNumber = random.nextInt(max + 1 - min) + min; 

Note that the both lower and upper limits are inclusive.

like image 102
Mark Byers Avatar answered Sep 23 '22 16:09

Mark Byers


You can use Random.nextInt(n). This returns a random int in [0,n). Just using max-min+1 in place of n and adding min to the answer will give a value in the desired range.

like image 26
MAK Avatar answered Sep 22 '22 16:09

MAK