1 Random概述和基本使用
import java.util.Random;
/*
Random用来生成随机的数字:
1. 导包
import java.util.Random;
2. 创建
Random r = new Random();
3. 使用
获取一个int型随机数字(范围是int所有范围 正负都有): int num = r.nextInt()
*/
public class Demo01Random {
public static void main(String[] args) {
Random r = new Random();
int num = r.nextInt();
System.out.println("随机数是:" + num);
}
}
2 Random生成指定范围内的随机数
import java.util.Random;
public class Demo02Random {
public static void main(String[] args) {
Random r = new Random();
for(int i = 0; i < 100; i++) {
int num = r.nextInt(10);
//int num = r.nextInt(10);r的范围是[0,9)
System.out.println(num);
}
}
}
3 Random练习1
/*
要求:根据int变量n的值,来获取随机数字,范围是[1,n]
*/
import java.util.Random;
public class Demo03Random {
public static void main(String[] args) {
int n = 5;
Random r = new Random();
for(int i = 0; i < 100; i++) {//打印100个处于[1,5]范围的随机数
int result = r.nextInt(n) + 1;
System.out.println(result);
}
}
}
4 Random练习2
/*
用代码模拟猜数字小游戏:采用二分法来猜
*/
import java.util.Random;
import java.util.Scanner;
public class Demo04RandomGame {
public static void main(String[] args) {
Random r = new Random();
int randomNum = r.nextInt(100) + 1;//[1,100]
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("请输入你猜测的数字:");
int guessNum = sc.nextInt();//键盘输入猜测的数字
if (guessNum > randomNum) {
System.out.println("太大了,请重试");
} else if (guessNum < randomNum) {
System.out.println("太小了,请重试");
} else {
System.out.println("恭喜你,猜对啦!");
break;
}
}
}
}
原文地址:https://www.cnblogs.com/deer-cen/p/12210014.html
时间: 2024-10-30 15:31:04