Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A number generation program....

 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
random.nextInt(49) + 1
 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Paul:
random.nextInt(49) + 1

 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cheers!
I get it now
 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Notice that we are adding one to the result of the method not the parameter passed to the method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic