I am using new Random().nextInt(999999)
to generate a 6 digit random number. But sometimes it generates 5 digit numbers. And I explicitly have to check if generated number is not 6 digit.
Why this method does that? And is there any other way to be pretty sure it generate only 6 digit random number.
答案 0 :(得分:4)
Random().nextInt(999999)
generates number between 0 and 999998, so you have ~10% chance to get number smaller than 100000 (5 and less digits).
Try
100000 + Random().nextInt(900000)
you will get number in range 100000 - 999999
答案 1 :(得分:0)
Random().nextInt(999999)
generates 5 digits number sometimes, because it generates random values between 0 and 999999.
Use the following snippet for generating random numbers in a range:
Random random = new Random();
minimum + random.nextInt(maximum - minimum + 1);