51

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?

informatik01
16.5k11 gold badges82 silver badges112 bronze badges
asked Mar 14, 2010 at 22:20
3
  • Did you forget to declare random and assign a new instance of java.util.Random to it? Commented Mar 14, 2010 at 22:48
  • could you explain how to do that? Commented Mar 14, 2010 at 23:02
  • Did you declare import statements for java.util.Random Commented Nov 22, 2012 at 10:12

8 Answers 8

147

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.

Dmitry Ryadnenko
22.6k4 gold badges44 silver badges58 bronze badges
answered Mar 14, 2010 at 22:22
Sign up to request clarification or add additional context in comments.

12 Comments

i updated the question with the error that occurs when i try to do that what is going wrong?
David, you need to instantiate it first. Random random = new Random(); It's still just Java code. There's no means of magic ;)
And make sure that you only instantiate the Random object once and reuse it. Don't create a new Random object for each call to your function.
You are missing import java.util.Random;.
@ataulm: In older versions of Java creating multiple Random objects didn't guarantee randomness. "Two Random objects created within the same millisecond will have the same sequence of random numbers." (source). In newer versions it is probably OK, but I didn't know that when I wrote my comment three years ago.
|
19

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.

informatik01
16.5k11 gold badges82 silver badges112 bronze badges
answered Mar 14, 2010 at 22:26

1 Comment

i updated the question with the error that occurs when i try to do that what is going wrong?
10
public static int random_int(int Min, int Max)
{
 return (int) (Math.random()*(Max-Min))+Min;
}
random_int(5, 9); // For example
Alexis Pigeon
7,52811 gold badges41 silver badges46 bronze badges
answered Jun 30, 2014 at 11:03

3 Comments

Your algorithm is Random x * positive number + positive number. How can this always result in a number between max and min?
Random is between 0 and 1. Do the math.
Be aware that the lower limit is inclusive but the upper limit is exclusive in this answer. If you wants both to be inclusive use: return (int) (Math.random()*(Max-Min + 1))+Min;
4

With Java 7 or above you could use

ThreadLocalRandom.current().nextInt(int origin, int bound)

Javadoc: ThreadLocalRandom.nextInt

answered Feb 1, 2019 at 15:40

Comments

4

As the solutions above do not consider the possible overflow of doing max-min when min is negative, here another solution (similar to the one of kerouac)

public static int getRandom(int min, int max) {
 if (min > max) {
 throw new IllegalArgumentException("Min " + min + " greater than max " + max);
 } 
 return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}

this works even if you call it with:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 
Ced
1,5676 gold badges24 silver badges36 bronze badges
answered Dec 5, 2016 at 22:46

Comments

1

Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :

min + (int) (Math.random() * (max - min + 1));
answered Sep 13, 2016 at 18:26

Comments

-3

This generates a random integer of size psize

public static Integer getRandom(Integer pSize) {
 if(pSize<=0) {
 return null;
 }
 Double min_d = Math.pow(10, pSize.doubleValue()-1D);
 Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
 int min = min_d.intValue();
 int max = max_d.intValue();
 return RAND.nextInt(max-min) + min;
}
javanna
60.4k14 gold badges147 silver badges125 bronze badges
answered May 12, 2011 at 22:59

1 Comment

That seems a complex way of achieving something that can be done in a single line of code. Please use code formatting in future.
-6

import java.util.Random;

answered Mar 14, 2010 at 23:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.