Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assured 6 digit random number

Tags:

java

random

scala

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
like image 665
Govind Singh Avatar asked May 13 '14 04:05

Govind Singh


2 Answers

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()
like image 115
merlin2011 Avatar answered Oct 05 '22 13:10

merlin2011


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.

like image 37
Dmitry Zagorulkin Avatar answered Oct 05 '22 13:10

Dmitry Zagorulkin