java之for循环⽣成随机数,多次数据均为重复
⼀:出现问题的代码
//⽣成⼿机号码个数
int phonedata=${__Random(1,500,)};
StringBuffer phonedatalist = new StringBuffer();
for (int i=0;i<phonedata;i++){
////⽣成⼿机号码后8位
phonedata1=${__time(/1000000,)};
String phonedata12=String.valueOf(phonedata1);
//随机选取⼿机前三位
int phonedata=${__Random(0,27,)};
java生成随机数的方法String[] phonelist = {"198","166","199","170","170","171","176","175","145","149","173","172","170","170","131","130","188","187","183","182","159","157","152","151","150","147","139","138"}; String phonedata2=phonelist[phonedata];
//随机选取⼿机第四位
int phonedata31=${__Random(0,9,)};
String phonedata311=String.valueOf(phonedata31);
//拼装成⼿机号码
String phone=phonedata2+phonedata311+phonedata12;
phonedatalist.append(phone).append(",");
}
⼆:修改之后的代码
//⽣成⼿机号码个数
int phonedata=${__Random(1,500,)};
StringBuffer phonedatalist = new StringBuffer();
Random rand = new Random();
for (int i=0;i<phonedata;i++){
//⽣成⼿机号码后8位
Int(9999999) + 1000000;
String phonedata12=String.valueOf(phonedata1);
//随机选取⼿机前三位
int Int(27) + 0;
String[] phonelist = {"198","166","199","170","170","171","176","175","145","149","173","172","170","170","131","130","188","187","183","182","159","157","152","151","150","147","139","138"}; String phonedata2=phonelist[phonedata];
//随机选取⼿机第四位
int Int(9) + 0;
String phonedata311=String.valueOf(phonedata31);
//拼装成⼿机号码
String phone=phonedata2+phonedata311+phonedata12;
phonedatalist.append(phone).append(",");
}
三:问题原因
1、问题还是出在随机函数定义位置上,函数定义不能放在for循环⾥⾯,⽽是应该在for循环外⾯定义好。
引⽤其他地⽅学到东西:⾸先就是要知道伪随机数Random的算法原理,其原理简单来说:⼀个种⼦ ---〉经过⼀定的算法 --〉产⽣⼀个结果(同时更改种⼦本⾝)那么.Next 的时候新的种⼦ ---〉经过⼀定
的算法 --〉产⽣另⼀个结果(同时再产⽣⼀个种⼦)通过这样得到随机的效果,也就是说如果初始种⼦⼀样,那么后⾯得到的结果和顺序基本上就是⼀样的,

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。