Mind you, if the smallest value you're allowed to have is 1, then use:
int number = (int ) (Math.random() * 20) + 1 ;
Main Topics
Browse All TopicsHi,
How unique random numbers within a range(eg. 1 to 20) can be generated in Java?
Regards.
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
If you are so much particular about UNIQUE random number, please follow the link which discuss about pseudo random number. http://mindprod.com/jgloss
If by 'unique' you mean the numbers must be different each time, you need to use a array. Maybe this is a homework assignment so I'll leave the details to you. Start with all of the allowed numbers in an array. Choose a number from 0 to 19 and read the number from that position in the array. Replace it by the last item(19) and next time choose a number from 0 to 18 etc.
public class RandomGenerator {
private boolean[] used;
private int generated;
public RandomGenerator( int max )
{
used = new boolean[max];
reset();
}
public void reset() {
for( int i = 0; i < max; i++ )
used[i] = false;
generated = 0;
}
public int getNextRandom() {
if( generated == max )
throw new Exception( "Cannot generated more UNIQUE numbers!" );
int index = (int)(Math.random() * max);
while( used[index] )
index = (int)(Math.random() * max);
used[index] = true;
generated++;
return index;
}
}
Business Accounts
Answer for Membership
by: InteractiveMindPosted on 2005-11-23 at 01:01:32ID: 15348525
int number = (int ) (Math.random() * (20+1)) ;