生成1~100之间的整数:
猜数字游戏:
import java.util.Random;
import java.util.Scanner;
//猜数字游戏
public class Demo02 {
public static void main(String[] args){
Random r = new Random();
int number = r.nextInt(100)+1;
while(true){
System.out.println("请输入你猜的数字:");
Scanner s = new Scanner(System.in);
int input = s.nextInt();
if(input == number){
System.out.println("猜对了");
break;
}else if(input > number){
System.out.println("猜大了");
}else{
System.out.println("猜小了");
}
}
}
}
运行结果:
保底机制情况示例:
import java.util.Random;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args){
Random r = new Random();
int number = r.nextInt(100)+1;
int count = 0;
System.out.println(number);
while(true){
System.out.println("请输入你猜的数字:");
Scanner s = new Scanner(System.in);
int input = s.nextInt();
//保底机制:不管猜得对不对,结果都输出"猜对了"
count++;
if(count==3){
System.out.println("猜对了");
break;
}
if(input == number){
System.out.println("猜对了");
break;
}else if(input > number){
System.out.println("猜大了");
}else{
System.out.println("猜小了");
}
}
}
}
运行结果: