Results 1 to 9 of 9
 06212008, 09:52 PM #1Member
 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, inclusivehow 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.

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.
 06212008, 10:57 PM #3Member
 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.
 06222008, 03:21 AM #4
use else/if statement to filter the undesired generated integer number....
freedom exists in the world of ideas
 06222008, 03:25 AM #5Java 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); } }

 06222008, 03:58 AM #7Member
 Join Date
 Jun 2008
 Posts
 20
 Rep Power
 0
Ok, thanks. I searched extensively and didn't come across anything.
 06222008, 05:07 AM #8
rand(max  min) + min.
My IP address is 127.0.0.1
 04192009, 05:50 PM #9Member
 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(ba)
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,
DavidLast edited by DavidG24; 04192009 at 06:04 PM.
Similar Threads

Random numbers
By jithan in forum Advanced JavaReplies: 3Last Post: 06142008, 02:04 PM 
random numbers without random class`
By carlos123 in forum New To JavaReplies: 4Last Post: 01172008, 11:44 PM 
random numbers
By carlos123 in forum New To JavaReplies: 1Last Post: 12222007, 03:56 AM 
Generate a random number
By romina in forum New To JavaReplies: 1Last Post: 08072007, 05:23 AM 
How to generate random number in java
By fernando in forum New To JavaReplies: 1Last Post: 08012007, 07:32 PM
Bookmarks