请问Random中的nextInt()和nextInt(int n)的区别是什么?

kayej 2005-09-29 05:54:35
请问Random中的nextInt()和nextInt(int n)的区别是什么?

nextInt(100) 可以产生100以内的随机数

而用nextInt()也可以呀:
Random random = new Random();
int a = (random.nextInt(100) >>> 1) % 100;

那他们有什么区别,用于什么不同的情况?
...全文
67975 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Tomcat4 2005-10-18
  • 打赏
  • 举报
回复
谁能解释一下nextInt(n)为什么不设计成静态方法啊?
shine333 2005-10-17
  • 打赏
  • 举报
回复
nextInt() [0, 31]
nextInt(n) [0, n-1]
sherrywang 2005-10-17
  • 打赏
  • 举报
回复
要import进哪个类,为什么rumlee(rum-lee) 的代码编译不了呢?
import java.util.*;
import java.io.*;
congliu 2005-09-29
  • 打赏
  • 举报
回复
nextInt()是无范围的随机数
但是nextInt(n)是从0到n的随机数
rumlee 2005-09-29
  • 打赏
  • 举报
回复
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");

if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);

int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}



public int nextInt() { return next(32); }


这是源代码,看看就知道有什么不同了。
xtrx 2005-09-29
  • 打赏
  • 举报
回复
下面的这段摘自java2 sdk的文档
int nextInt()
Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

int nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

我觉得从效果上没有大的区别,内在实现不同。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧