在不使用Math.Random的情况下如何生成随机数? [英] How can I generate a random number without use of Math.Random?

查看:374
本文介绍了在不使用Math.Random的情况下如何生成随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目需要我创建一个使用JOptionPane而不使用Math.Random来创建随机值的基本数字猜谜游戏.您将如何去做呢?除了随机数生成器,我已经完成了所有工作.谢谢!

My project entails that I create a basic number guessing game that uses the JOptionPane and does not use Math.Random to create the random value. How would you go about doing this? I've completed everything except the random number generator. Thanks!

推荐答案

以下是简单随机生成器的代码:

Here the code for a Simple random generator:

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)",您可以找到如何它在这里起作用.

The code above is a "Linear congruential generator (LCG)", you can find a good description of how it works here.

免责声明:

以上代码仅用于研究目的,不能作为 替换为股票Random或SecureRandom.

The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom.

这篇关于在不使用Math.Random的情况下如何生成随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆