math.random, only generating a 0?

Solution 1:

You are using Math.random() which states

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

You are casting the result to an int, which returns the integer part of the value, thus 0.

Then 1 + 0 - 1 = 0.

Consider using java.util.Random

Random rand = new Random();
System.out.println(rand.nextInt(3) + 1);

Solution 2:

Math.random() generates double values between range - [0.0, 1.0). And then you have typecasted the result to an int:

(int)Math.random()   // this will always be `0`

And then multiply by 3 is 0. So, your expression is really:

1 + 0 - 1

I guess you want to put parenthesis like this:

1 + (int)(Math.random() * 3)

Having said that, you should really use Random#nextInt(int) method if you want to generate integer values in some range. It is more efficient than using Math#random().

You can use it like this:

Random rand = new Random();
int croll = 1 + rand.nextInt(3);

See also:

  • Math.random() versus Random.nextInt(int)