# Random Numbers from 1 onwards

Printable View

• 12-18-2008, 02:50 AM
Ciwan
Random Numbers from 1 onwards
Hi Guys

can somone please tell me what I need to do to the nextInt (int n) to make it generate numbers starting at 1 and not 0.

Thanks
• 12-18-2008, 03:01 AM
Fubarable
I've always found that adding 1 to the result works well for me.

i.e., if I want a random int from 1 to 10:
Code:

```int max = 10; Random random = new Random(); int myRandomInt = random.nextInt(max) + 1; //violá```
• 12-18-2008, 03:03 AM
Ciwan
can you show me an example of what you mean please :(
• 12-18-2008, 03:03 AM
Fubarable
look above
• 12-18-2008, 03:03 AM
CJSLMAN
hhhmmm...
A couple of ideas:
Code:

```if (n==0)  {   n=1;  }```
or
Code:

`int randInt = rand.nextInt(n) [B]+ 1[/B];`
not sure on the syntax of the above, but you get the idea

Luck,
CJSL
• 12-18-2008, 04:31 AM
CJSLMAN
What?
How in hell did you do that Furball? :) That was sneaky... Oh, well... the OP now has lots of options to pick from....
And speaking of the OP, Ciwan, what do you mean you need an example? Fubarable's post is a complete and functional example (more code than I posted).

CJSL
• 12-18-2008, 07:21 AM
neilcoffey
By the way, always add 1. If you do the other suggestion (testing for 0 and replacing with 1), then the result will be biased towards producing 1 (since there are now two values that can end up with this number).
• 12-18-2008, 03:31 PM
Ciwan
Quote:

Originally Posted by CJSLMAN
Ciwan, what do you mean you need an example? Fubarable's post is a complete and functional example (more code than I posted)

Hi Guys

Thank you very much Fubarable :) that worked perfectly :D

@CJSLMAN: when I asked Fubarable for an example, he did not have an example up ! that came after I asked :)

Anywhoo Thank you for all your help :)