java 生成随机数

法 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));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_1403034144

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值