Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# random number gene betwn 2 no's

Mahesh Pinnamaneni
Ranch Hand
Posts: 100
hai dudes,
i need to generate random numbers(ofcourse using Math.random()) between the 2 numbers only(say i need to generate no's betwn 1 and 50 only).how can we achieve this.

thankQ
Bye
Mahesh

somkiat puisungnoen
Ranch Hand
Posts: 1312
I think , java.util.Random class is easy to use more than java.lang.Math.random() method...

So, if you want to random number between 2 number.

Example random 1 - 50

Ko Ko Naing
Ranch Hand
Posts: 3178
Originally posted by Somkiat Puisungnoen:

Mmm, Pui, I guess you forgot to have a look at the API that the parameter is exclusive.. So 50 won't be included in the randomized numbers... Instead of no = r.nextInt(50);, it should be no = r.nextInt(51); so that 50 is included in the randomized numbers...

Am I a bug fixer? :roll: Anyway, I hope the original poster gets what he wants correctly...

somkiat puisungnoen
Ranch Hand
Posts: 1312

Mahesh Pinnamaneni
Ranch Hand
Posts: 100
Dear Friends,
Thanks alot for ur ans but i hope the ans u have provided is not satisfactory , becoz i need to generate random numbers between 2 numbers i.e say betwn 10 and 50 or 50 and 100 etc and not just 0 and 10,50 etc.
the solution u have given is only for numbers betwn 0 and 20,30 likewise .
Hope u got my Q
regards,
Mahesh

Nick George
Ranch Hand
Posts: 815
look into the '+' operator, when applied to int,int

Tony Morris
Ranch Hand
Posts: 1608
[ September 07, 2004: Message edited by: Tony Morris ]

Max Rahder
Ranch Hand
Posts: 177
Just use Random#nextInt(int), for example:

Note that there are issues relating to initial seed values when creating a random number generator. You should read the API documentation for details.

fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
you need to figure out the range of possible values. if i want a number between 1 and 10, inclusive on both ends, there are 10. between 8 and 24 (inclusive) - 17.

generate a random integer that is less than the range. so in my second example, i would try to make a random number between 0 and 16 inclusive.

then, you need to figure out the offset. in my second example, my offset is 8. so, add 8 to my generated number.