avatar

Java常用类_Random类

Random类


1. Random类介绍

Random类 : 用来生成随机数字
Random类使用方法:

    1. 导包
1
import java.util.Random;
    1. 创建
1
Random r = new Random();
    1. 使用
1
int num = r.nextInt(); // 获取一个随机的int数字,创建数字的范围是Integer.MIN_VALUE到Integer.MAX_VALUE;

如果nextInt()方法中传入参数,则会在指定范围内生成随机数(一定是整数)

1
2
3
4
// 会在 [0,10)之间生成随机数
Random r = new Random();
int num = r.nextInt(10); // 传入的参数必须是正数,如果传入的是1,自然每次生成的都是0
System.out.println(num);
Author: TheOutsider
Link: http://yoursite.com/2020/03/30/Java%E5%B8%B8%E7%94%A8%E7%B1%BB-Random%E7%B1%BB/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.