保证6位数的随机数 [英] Assured 6 digit random number
本文介绍了保证6位数的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须生成一个6位数的随机数。以下是我到目前为止所做的守则。它工作正常,但有时候用 7位代替 6位。
主要问题是为什么?
如何生成一个有保证的6位数随机数?
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
推荐答案
如果 ran.nextInt()
返回的数字大于 900000
,则总和将是一个7位数字。
If ran.nextInt()
returns a number larger than 900000
, then the sum will be a 7 digit number.
修复是为了确保不会发生这种情况。自 Random.nextInt(n )
返回一个小于 n
的数字,以下内容将有效。
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()
这篇关于保证6位数的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文