Govind Singh Nagarkoti - 6 months ago 11x

Java Question

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

Answer

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()
```

Source (Stackoverflow)

Comments