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
Starting
Scala 2.13
,scala.util.Random
provides:def between(minInclusive: Int, maxExclusive: Int): Int
which used as follow, generates a 6-digit
Int
(between100_000
(included) and1_000_000
(excluded)):If you want a random number which can start with zeros, consider this:
If
ran.nextInt()
returns a number larger than900000
, 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 thann
, the following will work.Another approach, for
consider a vector of
6
random digits,Then, cast the vector onto an integral value,
This proceeding is general enough to cope with any number of digits. If
Long
cannot represent the vector, considerBigInt
.Update
Moreover, wrap it into an implicit class, noting that the first digit ought not be zero,
so it can be used as
It's because
nextInt()
Returns a pseudorandom, uniformly distributedint
value between 0 (inclusive) and the specified value (exclusive)You have to decrease your right border on one.