publicclassRandomDemo1{publicstaticvoidmain(String[] args){
Random r =newRandom();
System.out.println("在5-12中生成5个随机数:");for(int i =0; i <5; i++){int data = r.nextInt(8)+5;// r.nextInt(8)生成0-7不包含8的随机数
System.out.print(data +"\t");}}}
在5-12中生成5个随机数:
10125106
【Random类案例】猜数字游戏
随机生成一个1-100之间的数字,提示用户猜测,猜大提示过大,猜小提示过小,直到猜中结束
import java.util.Random;import java.util.Scanner;publicclassRandomDemo2{publicstaticvoidmain(String[] args){
Random r =newRandom();int number = r.nextInt(100)+1;
Scanner sc =newScanner(System.in);while(true){
System.out.println("请输入您在1-100中猜测的数字:");int guessNumber = sc.nextInt();if(guessNumber > number){
System.out.println("您猜测的数字过大!");}elseif(guessNumber < number){
System.out.println("你猜测的数字过小!");}else{
System.out.println("恭喜您,猜中了!正确数字为"+ number);// 猜中结束循环break;}}}}