Win a copy of Penetration Testing Basics this week in the Security forum!

# A number generation program....

Steve Jensen
Ranch Hand
Posts: 126
Folks,
Below is a piece of code which generates an int value, at random, six times.

Thing is, the numbers are randomly generated from anything between the upper and lower bound limits of int.
How can I make it so that the numbers generated, are within the range 1 - 49 ?

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
random.nextInt(49) + 1

Steve Jensen
Ranch Hand
Posts: 126
Originally posted by Thomas Paul:
random.nextInt(49) + 1

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
random.nextInt(49) generates a random integer from 0 to 48. Add 1 to the result and you get a range of 1 to 49.

Steve Jensen
Ranch Hand
Posts: 126
Cheers!
I get it now

Steve Jensen
Ranch Hand
Posts: 126
Originally posted by Thomas Paul:
random.nextInt(49) generates a random integer from 0 to 48. Add 1 to the result and you get a range of 1 to 49.

random.nextInt(49) + 1

Couldn't we just have said
random.nextInt(50)
to generate number between 1 and 49 inclusive.

[ February 14, 2003: Message edited by: Steve Jensen ]

Marilyn de Queiroz
Sheriff
Posts: 9067
12
random() always starts at zero so random.nextInt(50) would give you random numbers from 0 through 49 not from 1 through 49.

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
Notice that we are adding one to the result of the method not the parameter passed to the method.