-6

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.

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85

2 Answers2

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

StuartLC
  • 104,537
  • 17
  • 209
  • 285
mleko
  • 11,650
  • 6
  • 50
  • 71
  • [`Random.nextInt(int)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) returns a value **exclusive** to the limit. – Elliott Frisch Nov 13 '17 at 06:22
  • 1
    This answer is correct except Random().nextInt(999999) generates number between 0 and **999998** – Thracian Nov 13 '17 at 06:22
  • @ElliottFrisch, Fatih Ozcan thanks, I fixed my answer – mleko Nov 13 '17 at 06:24
  • Can someone please delete the question,please? – Mehraj Malik Nov 13 '17 at 08:49
  • @MehrajMalik Why? It has an upvoted answer that will help others as well. – Modus Tollens Nov 13 '17 at 08:53
  • @ModusTollens My question is continuously being down voted and eating my reputations, that's why. And because it's duplicate – Mehraj Malik Nov 13 '17 at 08:55
  • @MehrajMalik Questions that have an upvoted answer cannot be deleted because it would delete the answer as well, and that would be unfair to the users who answered. You can try to make your question more specific by editing it, that might get it reopened. You could also ask to have your question disassociated from your account by using the "contact us" link in this sites footer. – Modus Tollens Nov 13 '17 at 08:58
  • When I try to hover at **delete** option. it says **Two more votes needed to delete the question** someone has already requested to delete as it shows me **delete(1)**. – Mehraj Malik Nov 13 '17 at 09:01
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);
Lakshmikant Deshpande
  • 826
  • 1
  • 12
  • 30