法 1 new Random()
简单例子
Random rand = new Random();
int week = rand.nextInt(max);
生成 [0, max] 范围的数
代码
package s1_switch;
import java.util.Random;
public class 随机数 {
public static void main(String[] args) {
Random rand = new Random();
rand.setSeed(0);
// int t1 = rand.nextInt();
// int t2 = rand.nextInt(100);
// long t7 = rand.nextLong();
// float t5 = rand.nextFloat();
// double t3 = rand.nextDouble();
// double t4 = rand.nextGaussian();
boolean t6 = rand.nextBoolean();
System.out.println("t = " + t6);
}
}
详情
Random rand = new Random();
之后跟的代码
例如 | 解释 |
---|---|
rand.nextInt() | 均匀分布 |
rand.nextInt(n) | [ 0, n ) 的均匀分布 |
rand.nextInt()%n | ( -n, n ) 均匀分布 |
rand.nextLong() | 均匀分布的 long 值 |
rand.nextFloat() | [ 0,1) 之间的均匀 float 数 |
rand.nextDouble() | [ 0,1) 之间的均匀 double 数 |
rand.nextGaussian() | 正态分布 均值 0、标准差 1 |
rand.nextBoolean() | true 、false随机取 |
rand.setSeed(0); 用在 rand.nextBoolean(); 之前,若有这句代码,则随机数固定! | |
所以这句代码一般不写 |
法 2
double t = Math.random();
[ 0, 1 ) 之间随机取数 - double类型
保留两位小数
float f = 23.872385f;
DecimalFormat df =new DecimalFormat("#0.00");
String result = df.format(f);
随机获取hashmap的内容
private static HashMap<String,String> networkAttrMap;
static {
networkAttrMap = new HashMap<>();
networkAttrMap.put("08","内网");
networkAttrMap.put("24","红");
networkAttrMap.put("25","黄");
networkAttrMap.put("35","绿");
networkAttrMap.put("46","其它");
}
public static void main(String[] args) {
List<String> list = new ArrayList<>(networkAttrMap.keySet());
int pos = new Random().nextInt(list.size());
System.out.println(list.get(pos));
}