(int) ((Math.random() * 9 + 1) * 1000) //这里是随机4位数。需要几位数,就乘以几个零。
(int) ((Math.random() * 9 + 1) * 100) //随机3位数
(int) ((Math.random() * 9 + 1) * 10) //随机2位数
来个方法吧:
/**
* 获取随机位数的阿拉伯数字
* @param bit 位数
* @return int 生成的阿拉伯数字
**/
public static int randomArab(int bit){
return (int) ((Math.random() * 9 + 1) * Math.pow(10, bit - 1));
}
补充:
这里使用的是java.lang.Math类的random()方法,其内部使用的java.util.Random。
Random生成的随机数不是安全的随机数,在安全应用场景,随机数应该使用安全的随机数。密码学意义上的安全随机数,要求必须保证其不可预测性,可以使用java.Security.SecureRandom来生成。
一般情况下,我们使用Random即可。