System.currentTimeMillis()

通过System.currentTimeMillis()来获取随机数,实际上是获取当前时间毫秒数,它是long类型

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @author LeDao
* @company
* @create 2021-06-21 12:38
*/
public class Test {

public static void main(String[] args) {
long l = System.currentTimeMillis();
System.out.println(l);
}
}

Math.random()

它返回的是0(包含)到1(不包含)之间的double值,如果要返回[0,100]的int整数,只需要将获得的结果乘以100再转换为int类型即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @author LeDao
* @company
* @create 2021-06-21 12:38
*/
public class Test {

public static void main(String[] args) {
//[0,1)
double d = Math.random();
System.out.println(d);
//[0,100]
int i = (int) (d * 100);
System.out.println(i);
}
}

Random.nextInt(int bound)

获取[0,bound-1]的int整数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Random;

/**
* @author LeDao
* @company
* @create 2021-06-21 12:38
*/
public class Test {

public static void main(String[] args) {
Random random = new Random();
//[0,99]
int i = random.nextInt(100);
System.out.println(i);
}
}