# Thread: How do I generate random numbers in a certain range using the random class?

1. Member Join Date
Jun 2008
Posts
20
Rep Power
0

## How do I generate random numbers in a certain range using the random class?

I know how to use Math.random for this, but how would I generate random numbers using the random class?

Say I want a number between 40 and 50, inclusive--how would I do this?

What i have in mind is:

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

where max is 50 and min is 40. Is this correct?

Thank you.  Reply With Quote

2. ## Random numbers always go from 0 to the max. And you know that you want to start with 40 and add a random number to it. So how do you do this? Think on this and you will figure this out.  Reply With Quote

3. Member Join Date
Jun 2008
Posts
20
Rep Power
0

## I have searched it for the past 30 min and did not find an exact method for int. Can anyone help me out here? I need this before proceeding with my program.  Reply With Quote

4. ## use else/if statement to filter the undesired generated integer number....  Reply With Quote

5. ## Java Code:
```import java.util.Random;

public class Test {
public static void main(String[] args) {
Random seed = new Random();
// range [40 - 50]
int base = 40;
int variable = 10;
int min =  Integer.MAX_VALUE;
int max = -Integer.MAX_VALUE;
for(int i = 0; i < 100; i++) {
// 0 <= range returned < specified value
int next = 40 + seed.nextInt(variable + 1);
if(next < min) min = next;
if(next > max) max = next;
}
System.out.printf("min = %d  max = %d%n", min, max);
}
}```  Reply With Quote

6. ##  Originally Posted by frasifrasi I have searched it for the past 30 min and did not find an exact method for int. Can anyone help me out here? I need this before proceeding with my program.
You don't need an "exact method". We've given you enough hints, now all you need is a functioning brain.  Reply With Quote

7. Member Join Date
Jun 2008
Posts
20
Rep Power
0

## Ok, thanks. I searched extensively and didn't come across anything.  Reply With Quote

8. ## rand(max - min) + min.  Reply With Quote

9. Member Join Date
Apr 2009
Posts
49
Rep Power
0

## hey frasifrasi,

the method you have imposed is almost perfect,

if you wish to generate a random integer in the inclusive range a, b you must simply use the pseducode

rand = a + randominteger(b-a)

In Java code this becomes

Random R = new Random() //create Random Object
int random_number = min + R.nextInt(max - min + 1) //The reason you need the +1 is that nextInt(n) generates a random int from 0 inclusive to n exclusive, thus to generate from 0 to n, simply use nextInt(n + 1)

Hope this helps,

David
Last edited by DavidG24; 04-19-2009 at 07:04 PM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•