Random r = new Random(System.currentTimeMillis()); int rInt = r.nextInt(2); while (rInt != 2) { System.out.println(rInt); r = new Random(System.currentTimeMillis()); rInt = r.nextInt(2); } Why such a construction produces only 0 and 1?
Random r = new Random(System.currentTimeMillis()); int rInt = r.nextInt(2); while (rInt != 2) { System.out.println(rInt); r = new Random(System.currentTimeMillis()); rInt = r.nextInt(2); } Why such a construction produces only 0 and 1?
Because you specify to generate integer values from 0 to 2 not inclusive.
From the documentation:
public int nextInt (int bound) ... bound - the upper bound (exclusive)
That is, if you need to generate values from 0 to 2 inclusive, then you need to specify the value of the argument 3.
Because the nextInt(int n) method returns a random number in the range [0, n) , the value n itself is excluded from the range, which is clearly stated in the documentation :
Returns a pseudorandom uniformly distributed int value between 0 (inclusive) and the specified value ( exclusive )
Think of the argument n as the number of different numbers that you can get, starting with zero, from the extended natural series.
Source: https://ru.stackoverflow.com/questions/547943/
All Articles