Java: Can (new Random()).nextInt(5) always return the same number?

后端 未结 6 1623
温柔的废话
温柔的废话 2020-12-11 08:57

Sometimes this piece of code always returns the same number (and sometimes it works fine):

(new Random()).nextInt(5)

I have suspicions wher

6条回答
  •  时光取名叫无心
    2020-12-11 09:16

    The best way to approximate uniform distribution is to use the static method Random.nextInt(n) to produce integers in the range [0, n-1] (Yes, n is excluded). In your particular example, if you want integers in the range 0 to 5, inclusive, you would call Random.nextInt(6).

提交回复
热议问题