我设置种子时,Java随机总是返回相同的数字? [英] Java random always returns the same number when I set the seed?

查看:95
本文介绍了我设置种子时,Java随机总是返回相同的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助我正在创建的随机数生成器。我的代码如下(在一个名为数字的类中):

I require help with a random number generator I am creating. My code is as follows (inside a class called numbers):

public int random(int i){
    Random randnum = new Random();
    randnum.setSeed(123456789);
    return randnum.nextInt(i);
}

当我从另一个类调用此方法时(为了生成一个随机数) ),它总是返回相同的数字。例如,如果我这样做:

When I call this method from another class (in order to generate a random number), it always returns the same number. For example if I were to do:

System.out.println(numbers.random(10));
System.out.print(numbers.random(10));

它总是打印相同的数字,例如5 5.我必须做什么才能打印两个不同的数字,例如5 8

it always prints the same number e.g. 5 5. What do I have to do so that it prints two different numbers e.g. 5 8

我必须设置种子。

谢谢

推荐答案

您需要在整个班级中共享 Random()实例:

You need to share the Random() instance across the whole class:

public class Numbers {
    Random randnum;

    public Numbers() {
        randnum = new Random();
        randnum.setSeed(123456789);
    }

    public int random(int i){
        return randnum.nextInt(i);
    }
}

这篇关于我设置种子时,Java随机总是返回相同的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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