文章转载
JavaRandom的使用,上面的博客中,有比较详细的解释,我认为是比较全面的!
2019-01-11
实例
import java.util.Random;
/**
* @author yangyun
* @title
* @Package com.yangyun.thinkinginjava.chapter19.others
* @date 2019-01-11 15:02
*/
public class RandomTest {
public Random random = new Random(5);
/**
* Random初始化在方法里面
*
* @return
*/
public int next() {
Random rand = new Random(5);
// 这样随机数产生就对了
// Random rand = new Random();
int a = rand.nextInt(5);
return a;
}
/**
* 调用外面的
*
* @return
*/
public int nextn() {
int a = random.nextInt(5);
return a;
}
public static void main(String[] args) {
RandomTest test = new RandomTest();
for (int i = 0; i < 5; i++) {
System.out.println("next:" + test.next());
}
for (int i = 0; i < 5; i++) {
System.out.println("nextn:" + test.nextn());
}
}
}
# 结果
next:2
next:2
next:2
next:2
next:2
nextn:2
nextn:4
nextn:1
nextn:4
nextn:2
原因
Random() 默认种子,每次产生的随机数不同
Random(long seed)指定种子,每次种子相同,随机数就相同