math.random always give 0 result

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

    The Math.random() method returns a random double that is from 0 (inclusive) to 1 (exclusive). Performing % 10 doesn't affect this value, but casting it to an int truncates any decimal portion, always yielding 0.

    If you want a random number from 0-9, you can multiply Math.random() by 10, instead of taking the remainder when divided by 10.

    Alternatively, you can create a java.util.Random object and call nextInt(10).

提交回复
热议问题