David David - 4 months ago 8
Java Question

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

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
int
s)

that returns soemthing like this:

8


(randomly)

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

Update: atempting to implement the full solution in the nextInt answer I have this:

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 complier:

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?

Answer

Construct a Random object at application startup:

Random random = new Random();

Then use Random.nextInt(int):

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

Note that the lower limit is inclusive, but the upper limit is exclusive.

Comments