作用:生成随机数
使用:
package random;
import java.util.Random;
import java.util.Scanner;
public class RandomTest {
public static void main(String[] args) {
Random rd = new Random();
int n = rd.nextInt();
System.out.println(n);
int num = rd.nextInt(10); //重载
System.out.println(num); // 输出的数的范围是 [0,10) 0~9
Scanner sc = new Scanner(System.in);
System.out.println("请输入随机数的范围1~k:");
int k = sc.nextInt();
System.out.println(rd.nextInt(k)+1);
}
}
猜数小游戏
package random;
import java.util.Random;
import java.util.Scanner;
public class RandomGuess {
public static void main(String[] args) {
Random rd = new Random();
Scanner sc = new Scanner(System.in);
int n = rd.nextInt(100)+1;
int cnt = 0;
boolean flag = false;
while (true){
cnt++;
System.out.println("你一共有6次机会数字的范围是1~100这是你第"+cnt+"次猜数!!!");
System.out.println("请输入你猜的数");
int num = sc.nextInt();
if(num == n){
System.out.println("恭喜你猜对了!!!");
}else if(num>n){
System.out.println("你猜的数太大了!!!");
}else {
System.out.println("你猜的数太小了!!!");
}
if(cnt == 6){
System.out.println("机会已经用尽,谢谢参与!!!");
flag = true;
}
if(flag){
break;
}
}
}
}