Random类
简介
Random类位于java.util包中,主要用来生成随机数
使用方法
1.导包
import java.util.Random;
2.创建对象
Random r = new Random();
3.使用
// 方法一无参数使用
int num = r.nextInt();
// 方法二有参数使用
int num2 = r.nextInt(10)
方法一生成的既有**正数**,又有**负数**,范围在**int**范围内
方法二生成随机数的范围为左闭右开区间
例子中参数为10,故范围为[0,10),也就是0~9内的随机数
输出结果
-752778896
2
4.实现生成范围为[1,n]的随机数
分析:由于随机数的生成范围为[0,n),也就是0~n-1,所以应在nextInt(n)
外面+1,此时范围为[1,n]
import java.util.Random;
/*
根据int变量n的值,获取随机数字,范围是[1,n]
*/
public class Demo03Random {
public static void main(String[] args) {
int n = 10;
Random r = new Random();
for (int i = 0; i < 100; i++) {
int num = r.nextInt(n) + 1;
System.out.println(num);
}
}
}
输出结果:
10
2
8
2
5
8
10
10
4
4
1
7
10
9
9
5
4
2
10
10
6
8
10
1
1
7
4
实践
猜数字小游戏:随机生成一个1~100内的数字,用户输入一个数字,如果比随机数大,则提示“太大了”,反之提示“太小了”,知道猜到该数字。
package day07.demo03;
import java.util.Random;
import java.util.Scanner;
/*
猜数字
*/
public class Demo04Random {
public static void main(String[] args) {
Random r = new Random();
int num = r.nextInt(100) + 1;
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("请猜测一个数字");
int guessNum = sc.nextInt();
if(guessNum<num){
System.out.println("太小了");
}else if (guessNum>num){
System.out.println("太大了");
}else {
System.out.println("猜对了,数字为" + num);
break;
}
}
}
}
输出结果:
请猜测一个数字
50
太大了
请猜测一个数字
25
太小了
请猜测一个数字
40
太大了
请猜测一个数字
35
太大了
请猜测一个数字
30
太小了
请猜测一个数字
33
太小了
请猜测一个数字
34
猜对了,数字为34