简介:生成随机数
-
构造方法:
Random();
创建一个新的随机数生成器。
Random(long seed);
使用单个 long 种子创建一个新的随机数生成器。 -
常用方法:
方法 | 描述 |
---|---|
int nextInt() |
-2^31 ~ 2^31-1 int 值 |
nextInt(int bound) |
从 0 到 bound 值(不包含)随机数 |
boolean nextBoolean() |
随机 boolean 值 |
void nextBytes(byte[] bytes) |
随机字节并将其置于 byte 数组中 |
double nextDouble() |
0.0 ~ 1.0 之间 double 值 |
float nextFloat() |
0.0 ~ 1.0 之间 float 值 |
double nextGaussian() |
(“正态”)分布的 double 值,其平均值是 0.0 标准差是 1.0 |
long nextLong() |
随机 long 值 |
void setSeed(long seed) |
使用单个 long 种子,设置此随机数生成器的种子 |
- 案例:
Random random = new Random();
// nextInt() -2^31 ~ 2^31-1 int 值
// System.out.println(random.nextInt());
// nextInt(int bound) 从0到bound值(不包含)随机数,
// 小案例:随机点餐
String[] eat = new String[]{"茄子煲","糖醋排骨","蜂蜜炸鸡","酸菜鱼","卤猪蹄"};
System.out.println(eat[random.nextInt(eat.length)]);
// 生成 [0 ~ 1.0) 区间的小数 左闭右开
double d1 = r.nextDouble();
// 生成 [0 ~ 5.0) 区间的小数
double d2 = r.nextDouble() * 5;
// 生成 [1 ~ 2.5) 区间的小数
double d3 = r.nextDouble() * 1.5 + 1;
// 生成 -2^31 ~ 2^31-1 之间的整数
int n = r.nextInt();
// 生成 [0 ~ 10) 区间的整数
// 方法 1:
int n2 = r.nextInt(10);
// 方法 2:
int n3 = Math.abs(r.nextInt() % 10);
补充:Math.Random();
- 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0,取值范围是 [0.0,1.0) (左闭右开区间)
package com.base.demo05;
public class Demo06 {
public static void main(String[] args) {
random();
}
// Math.random();
// 随机数方法
private static void random() {
//产生一个[0,1)之间的随机数
double random = Math.random();
System.out.println(random);
}
}
网友评论