This week's book giveaway is in the Servlets forum. We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line! See this thread for details.

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.

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...

Co-author of SCMAD Exam Guide, Author of JMADPlus SCJP1.2, CCNA, SCWCD1.4, SCBCD1.3, SCMAD1.0, SCJA1.0, SCJP6.0

somkiat puisungnoen
Ranch Hand

Joined: Jul 04, 2003
Posts: 1312

posted

0

Thank you for your comment....

Mahesh Pinnamaneni
Ranch Hand

Joined: Jul 02, 2004
Posts: 100

posted

0

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

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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors