I have to Generate a 6 digit Random Number. The below is the Code that I have done so far. It works fine but some time its giving 7 digits in place of 6 digits.
The main question is why?
How do I generate an assured 6 digit random number?
val ran = new Random()
val code= (100000 + ran.nextInt(999999)).toString
If ran.nextInt()
returns a number larger than 900000
, then the sum will be a 7 digit number.
The fix is to make sure this does not happen. Since Random.nextInt(n)
returns a number that is less than n
, the following will work.
val code= (100000 + ran.nextInt(900000)).toString()
It's because nextInt()
Returns a pseudorandom, uniformly distributed int
value between 0 (inclusive) and the specified value (exclusive)
You have to decrease your right border on one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With