# Thread: Math.random() without a "0"

1. Senior Member
Join Date
Feb 2010
Posts
128
Rep Power
0

## Math.random() without a "0"

Hi Java fans, I've been writing a tic-tac-toe game. Im thinking of a way that would allow me to produce random digits between 1 and 3 included. I know Math.random() starts with a 0 but i really don't need it. Anyone have their own sort off techniques that could be shared?

Much appreciated

Thanks

2. Just add one to your result :)

Java Code:
```Random r = new Random();

int randValue = r.nextInt(3) + 1;```

3. Senior Member
Join Date
Feb 2010
Posts
128
Rep Power
0
Originally Posted by mrmatt1111
Just add one to your result :)

Java Code:
```Random r = new Random();

int randValue = r.nextInt(3) + 1;```

Hmmmmm...

but what if the random value turns out to be 3? 3+1 = 4 = Outof BoundsException

EDIT: AHHHHHHH...see i did not realise that you have used Random instead of Maths.random() My apologies. Thanks for the help.
Last edited by FlyNn; 03-01-2010 at 10:54 PM.

4. Math.random() should work also:

Java Code:
`int i = (int)(Math.random() * 3) + 1;`

5. Originally Posted by FlyNn
Hmmmmm...

but what if the random value turns out to be 3? 3+1 = 4 = Outof BoundsException
Hmmmm, boy this is tough,.... maybe you could limit your random numbers from 0-2 perhaps and then add 1? Nah, it can't be that simple, can it?

And there's no need to use Math.random() and have to cast to int. r.nextInt(2) + 1 would work just fine.

Just curious: did you try to figure this out yourself first before asking the forum?
Last edited by Fubarable; 03-02-2010 at 02:42 AM.

#### Posting Permissions

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