math.random always give 0 result

前端 未结 8 803
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 16:40

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

8条回答
  •  醉梦人生
    2021-01-29 17:18

    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);
    

提交回复
热议问题