I am using Ubuntu 14.04.3 LTS and I am studying Java from the book. I tried to follow one example on the book with Ubuntu Terminal and I\'m using Sublime Text. Here is the code
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);