# Math.random() without a "0"

• 03-01-2010, 10:23 PM
FlyNn
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
• 03-01-2010, 10:38 PM
mrmatt1111

Code:

```Random r = new Random(); int randValue = r.nextInt(3) + 1;```
• 03-01-2010, 10:40 PM
FlyNn
Quote:

Originally Posted by mrmatt1111

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.
• 03-01-2010, 11:29 PM
mrmatt1111
Math.random() should work also:

Code:

`int i = (int)(Math.random() * 3) + 1;`
• 03-02-2010, 02:24 AM
Fubarable
Quote:

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?