Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Random number

807605Aug 29 2007 — edited Aug 29 2007
I am trying to generate a random number between 1 to 50 using java.util.Random

using Random
int n = 50;
Random rand =  new Random();
int r = rand.nextInt(n+1);
The above code will give the random number between 0 to 50.
However, i do not want to generate 0.
In such case, how should i do it, is the following method a good way to do it
int n = 50;
Random rand = new Random();
int r = rand.nextInt(n)+1;
The above code gives the random number betwen 0 to 49 (as of API says).
Generating random number in this way is correct or should i look for
another approach?
Thank you.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 26 2007
Added on Aug 29 2007
2 comments
258 views