我的项目需要创建一个基本的猜数游戏,该游戏使用 JOptionPane 并且不使用 Math.Random 来创建随机值。你会怎样做呢?除了随机数生成器之外,我已经完成了所有内容。谢谢!
这是简单随机生成器的代码:
public class SimpleRandom {
/**
* Test code
*/
public static void main(String[] args) {
SimpleRandom rand = new SimpleRandom(10);
for (int i = 0; i < 25; i++) {
System.out.println(rand.nextInt());
}
}
private int max;
private int last;
// constructor that takes the max int
public SimpleRandom(int max){
this.max = max;
last = (int) (System.currentTimeMillis() % max);
}
// Note that the result can not be bigger then 32749
public int nextInt(){
last = (last * 32719 + 3) % 32749;
return last % max;
}
}
上面的代码是一个“线性同余生成器(LCG)”,你可以找到很好的描述这里是如何运作的。 https://en.wikipedia.org/wiki/Linear_congruential_generator
免责声明:
上面的代码仅供研究使用,不作为
替换为库存 Random 或 SecureRandom。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)