Scanner scanner = new Scanner(System.in);
System.out.println("现在开始游戏?(Y/N)");
String choice;
do {
choice = scanner.nextLine().toUpperCase();
while (!choice.equals("Y") && !choice.equals("N")) {
System.out.println("输入有误,请重新输入: ");
choice = scanner.nextLine().toUpperCase();
}
if (choice.equals("N")) {
System.out.println("已退出");
System.exit(0);
}
//生成一个1-100的目标数字
int target = (int) (Math.random() * 100 + 1);
int number;
int times = 1;
do {
System.out.print("请输入猜想的数字(1-100): ");
number = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
if (number > target) {
System.out.println("猜大了");
} else if (number < target) {
System.out.println("猜小了");
} else {
System.out.println("猜对了!本次猜对所用次数为" + times + "次");
times = 1;
break;
}
times++;
} while (true);
// 处理是否要继续游戏的选择
System.out.println("是否要继续游戏?(Y/N)");
choice = "";
if (!scanner.hasNextLine()) {
System.out.println("已退出");
System.exit(0);
}
choice = scanner.nextLine().toUpperCase();
while (!choice.equals("Y") && !choice.equals("N")) {
System.out.println("输入有误,请重新输入: ");
choice = scanner.nextLine().toUpperCase();
}
} while (!choice.equals("N"));
System.out.println("已退出");
}