java 随机,Java随机数不是随机的?

I was trying to explain the random number generator in Java to a friend when he kept getting the same numbers every time he ran the program. I created my own simpler version of the same thing and I too am getting the same exact numbers he was getting every time I run the program.

What am I doing wrong?

import java.util.*;

public class TestCode{

public static void main(String[] args){

int sum = 0;

Random rand = new Random(100);

for(int x = 0; x < 100; x++){

int num = (rand.nextInt(100)) + 1;

sum += num;

System.out.println("Random number:" + num);

}

//value never changes with repeated program executions.

System.out.println("Sum: " + sum);

}

}

The final five numbers out of the 100 are:

40

60

27

56

53

解决方案

You have seeded the random generator with a constant value 100. It's deterministic, so that will generate the same values each run.

I'm not sure why you chose to seed it with 100, but the seed value has nothing to do with the range of values that are generated (that's controlled by other means, such as the call to nextInt that you already have).

To get different values each time, use the Random constructor with no arguments, which uses the system time to seed the random generator.

Quoting from the Javadoc for the parameterless Random constructor:

Creates a new random number generator. This constructor sets the seed

of the random number generator to a value very likely to be distinct

from any other invocation of this constructor.

Quoting the actual code in the parameterless Random constructor:

public Random() {

this(seedUniquifier() ^ System.nanoTime());

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值