java如何猜年龄
实现猜年龄游戏的Java代码
以下是一个简单的Java程序,通过提问用户一系列问题来猜测用户的年龄。该程序使用二分查找算法逐步缩小年龄范围。
import java.util.Scanner;
public class AgeGuesser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int low = 1;
int high = 100;
int guess;
String response;
System.out.println("思考一个年龄在1到100之间,我会尝试猜出来。");
while (low <= high) {
guess = (low + high) / 2;
System.out.print("你的年龄是" + guess + "岁吗?(y/n) ");
response = scanner.nextLine().toLowerCase();
if (response.equals("y")) {
System.out.println("太好了!我猜对了!");
return;
}
System.out.print("你的年龄比" + guess + "岁大吗?(y/n) ");
response = scanner.nextLine().toLowerCase();
if (response.equals("y")) {
low = guess + 1;
} else {
high = guess - 1;
}
}
System.out.println("你的年龄是" + low + "岁!");
scanner.close();
}
}
算法原理
该程序使用二分查找算法来猜测年龄。它首先将年龄范围设为1到100岁,然后不断将范围缩小一半。
每次迭代中,程序计算当前范围的中间值作为猜测值。根据用户的反馈,调整搜索范围的上限或下限。如果用户年龄大于猜测值,则提高下限;否则降低上限。

程序优化方向
增加错误处理机制,防止用户输入无效字符。可以添加循环直到用户输入有效响应。
while (true) {
System.out.print("你的年龄比" + guess + "岁大吗?(y/n) ");
response = scanner.nextLine().toLowerCase();
if (response.equals("y") || response.equals("n")) {
break;
}
System.out.println("请输入y或n!");
}
添加猜测次数限制,防止无限循环。可以在while循环条件中加入计数器。

int attempts = 0;
while (low <= high && attempts < 10) {
attempts++;
// 原有代码
}
扩展功能
可以记录猜测历史,在最后显示所有猜测过程。创建数组存储每次猜测的值。
List<Integer> guessHistory = new ArrayList<>();
// 在猜测后添加
guessHistory.add(guess);
增加难度级别,让用户选择年龄范围。在程序开始时询问用户最大年龄。
System.out.print("请输入最大年龄限制: ");
high = scanner.nextInt();
scanner.nextLine(); // 消耗换行符






