package day03; /** * 第 3 天:猜数字游戏 —— while 循环 + if 判断 * 目标:掌握 while 循环和条件判断的配合使用 * * 游戏规则:程序随机生成 1-100 的数字,玩家最多猜 7 次, * 每次猜测后提示"大了"或"小了",猜中或次数用完则结束。 */ import java.util.Scanner; import java.util.Random; public class GuessNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random random = new Random(); // 生成 1~100 的随机整数 int target = random.nextInt(100) + 1; int maxAttempts = 7; // 最多猜 7 次 int attempts = 0; // 已猜次数 boolean guessed = false; System.out.println("========== 猜数字游戏 =========="); System.out.println("我已想好一个 1~100 之间的数字,你有 " + maxAttempts + " 次机会!"); // while 循环:当还有剩余次数且未猜中时继续 while (attempts < maxAttempts && !guessed) { attempts++; System.out.print("\n第 " + attempts + " 次猜测,请输入数字: "); int guess = scanner.nextInt(); if (guess < 1 || guess > 100) { System.out.println("请输入 1~100 之间的数字!"); attempts--; // 不浪费这次机会 continue; // 跳过本次循环剩余代码 } if (guess == target) { System.out.println("\n🎉 恭喜你猜对了!答案就是 " + target + "!"); System.out.println("你一共猜了 " + attempts + " 次。"); guessed = true; } else if (guess > target) { System.out.println("太大了!"); } else { System.out.println("太小了!"); } // 提示剩余次数 if (!guessed && attempts < maxAttempts) { System.out.println("还有 " + (maxAttempts - attempts) + " 次机会。"); } } // 没猜中的情况 if (!guessed) { System.out.println("\n😢 很遗憾,次数用完了!正确答案是 " + target + "。"); } scanner.close(); } }