实现说明
真正干活的是类 DiceSample和函数 main,其余都是接线。
使用要点
- 每一步打印都带着自己的标签:
draws:、replay sum :、stats :。
常见问题
运行「Random.ints 有界抽样流」会打印什么?
运行文件本身,draws:、replay sum :、stats : 这些前缀各对应一段演示逻辑。
核心语句
var stats = new Random(42).ints(5, 1, 7).summaryStatistics();
Random dice = new Random(42); // 固定种子:同种子同调用序列 = 相同结果
// ints(streamSize, origin, bound):origin 含、bound 不含
System.out.print("draws: ");
Random replay = new Random(42);
代码示例
import java.util.Random;
public class DiceSample {
public static void main(String[] args) {
Random dice = new Random(42); // 固定种子:同种子同调用序列 = 相同结果
// ints(streamSize, origin, bound):origin 含、bound 不含
System.out.print("draws: ");
dice.ints(5, 1, 7).forEach(d -> System.out.print(d + " "));
System.out.println();
// 重新播种同一序列:重放得到完全相同的 5 个数
Random replay = new Random(42);
System.out.println("replay sum : " + replay.ints(5, 1, 7).sum());
// 汇总统计直接挂在同一条流上
var stats = new Random(42).ints(5, 1, 7).summaryStatistics();
System.out.println("stats : " + stats);
}
}