Assured 6 digit random number

2019-04-08 20:13发布

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

8条回答
Evening l夕情丶
2楼-- · 2019-04-08 21:05
import scala.util.Random
math.ceil(Random.nextFloat()*1E6).toInt
查看更多
地球回转人心会变
3楼-- · 2019-04-08 21:12
val code= (100000 + ran.nextInt(999999)).toString

The problem is ran.nextInt(999999) might return number greater than 899999, which would result in 7-digit-number together if you add 100000.

Try change it to

val code= (100000 + ran.nextInt(899999)).toString

This will ensure your random number to be more than or equal to 100000 and less than or equal to 999999.

查看更多
登录 后发表回答