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

• 06-21-2008, 09:52 PM
frasifrasi
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.
• 06-21-2008, 10:51 PM
Fubarable
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.
• 06-21-2008, 10:57 PM
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.
• 06-22-2008, 03:21 AM
sukatoa
use else/if statement to filter the undesired generated integer number....
• 06-22-2008, 03:25 AM
hardwired
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);     } }```
• 06-22-2008, 03:31 AM
Fubarable
Quote:

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.
• 06-22-2008, 03:58 AM
frasifrasi
Ok, thanks. I searched extensively and didn't come across anything.
• 06-22-2008, 05:07 AM
Zosden
rand(max - min) + min.
• 04-19-2009, 05:50 PM
DavidG24
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