Math.random()
returns a double value between 0 (inclusive) and 1 (exclusive). It does not return an integer value. Therefore, when you take the number produced by Math.random()
modulo 10, it returns the same double value. The final cast to int
makes that value always 0.
Run the following code to see for yourself:
double random = Math.random();
System.out.println(random); // for example 0.5486395326203879
System.out.println(random % 10); // still 0.5486395326203879
System.out.println((int) (random % 10)); // outputs 0
What you really want is to use a Random
object and use Random.nextInt(bound)
. To have a random integer between 0 and 9, you can use:
Random random = new Random();
int value = random.nextInt(10);
solved math.random always give 0 result