Thread: Random Numbers from 1 onwards

1. Banned
Join Date
Dec 2008
Location
Earth
Posts
87
Rep Power
0

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

2. 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:
Java Code:
```int max = 10;
Random random = new Random();
int myRandomInt = random.nextInt(max) + 1; //violá```

3. Banned
Join Date
Dec 2008
Location
Earth
Posts
87
Rep Power
0
can you show me an example of what you mean please :(

4. hhhmmm...

A couple of ideas:
Java Code:
```if (n==0)
{
n=1;
}```
or
Java Code:
`int randInt = rand.nextInt(n) [B]+ 1[/B];`
not sure on the syntax of the above, but you get the idea

Luck,
CJSL

5. look above

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

7. Senior Member
Join Date
Nov 2008
Posts
286
Rep Power
9
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).

8. Banned
Join Date
Dec 2008
Location
Earth
Posts
87
Rep Power
0
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 :)

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•