Java Random giving negative numbers

2019-01-23 22:47发布

I'm having trouble with Javas Random class, if i do this:

Random rng = new Random(seed) // seed == 29 in this example

String ss = "";
        for(int i = 0; i < 10; i++)
        {
            int s = rng.nextInt();
            ss += Integer.toString(s);
            ss +="\n";
        }

This is what i get back:

-1169335537
-2076183625
1478047223
1914482305
722089687
2094672350
-1234724057
-1614953544
-321574001
1000360613

From what I have read this should only be returning positive numbers for a start?

This may be a bit far fetched but it couldnt have anything to do with running a 64 bit machine on Windows 7 64 bit?

Any help at all would be awesome need to get this finished for an assignment hand in today!

标签: java random
8条回答
啃猪蹄的小仙女
2楼-- · 2019-01-23 23:45

Check out the documentation for java.util.Random:

http://download.oracle.com/javase/6/docs/api/java/util/Random.html

Are you you trying to get random numbers from 0 to 28? If so, you need to use nextInt(int) as mentioned previously. The seed has no bearing on the range of possible outputs or their relative likelihoods.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-23 23:48

Negative numbers are allowed - maybe you've read of the similar Random method nextInt( int ) which does limit the returned values to be zero or greater.

查看更多
登录 后发表回答