用到了Random类的nextInt()方法生成随机数
nextInt(参数) 代表 [0,参数) 范围内取随机一个数
总共设定为十次机会,范围 [1,1024] (正好用二分查找找到哦)
log21024 = 10
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args){
Random r = new Random();
int x = r.nextInt(1024) + 1;//[1,1024]
System.out.println("范围为[1,1024],你总共有十次机会,请输入你猜的数字:");
int num = new Scanner(System.in).nextInt();
for(int i=0;i<9;i++) {
if (num > x){
System.out.println("偏大了,往小猜哦,你还剩"+(9-i)+"次机会");
System.out.println("请输入你猜的数字:");
num = new Scanner(System.in).nextInt();
//continue;
}
else if (num < x){
System.out.println("猜小了,往大猜!你还剩"+(9-i)+"次机会");
System.out.println("请输入你猜的数字:");
num = new Scanner(System.in).nextInt();
//continue;
}
else {
System.out.println("猜对啦!数字为"+num+"游戏结束");
return;
}
}
System.out.println("很遗憾,机会用完啦,游戏结束");
}
}