math.random always give 0 result

前端 未结 8 799
伪装坚强ぢ
伪装坚强ぢ 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:17

    public static double random()

    Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

    (source)

    It returns a double that satisfies 0.0 <= double < 1.0, therefore taking the modulo will always result in zero. I recommend the java.util.Random class to achieve what you need. Specifically Random.nextInt(int).

提交回复
热议问题