You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

猜数字游戏开发问题:连续重复输入同一数字仅计一次尝试次数

解决猜数字游戏中连续重复猜测的计数问题

Got it, let's fix this issue where consecutive duplicate guesses are counting as separate attempts. The core idea is to track the user's last guess and only increment the attempt count when the new guess is different from the previous one.

修改后的完整代码

import java.util.Random;
import java.util.Scanner;

public class GuessNumberGame {
    public static void main(String[] args) {
        int ans, guess;
        final int max = 10;
        Scanner jai = new Scanner(System.in);
        Random no = new Random();
        int att = 0;
        int lastGuess = 0; // 存储上一次的猜测值,初始值设为0(不在1-10范围内)
        ans = no.nextInt(max) + 1;

        while (true) {
            System.out.println("Enter a number between 1 to 10");
            guess = jai.nextInt();

            // 只有当前猜测和上一次不同时,才增加尝试次数
            if (guess != lastGuess) {
                att += 1;
                lastGuess = guess; // 更新上一次的猜测值
            }

            if (guess == ans) {
                System.out.println("You are correct, the answer is :" + ans);
                System.out.println(att + " attempts to find the correct number!");
                jai.close(); // 记得关闭Scanner资源
                System.exit(0);
            } else if (guess > ans) {
                System.out.println("Too Large");
            } else if (guess < ans) {
                System.out.println("Too Small");
            }
        }
    }
}

关键改动说明

  • 新增lastGuess变量:用来记录用户上一次输入的数字,初始值设为0(因为游戏范围是1-10,第一次输入肯定不会和0重复,确保首次猜测正常计数)。
  • 调整尝试计数逻辑:不再每次输入都直接增加att,而是判断当前猜测是否和上一次相同。只有当两者不同时,才递增尝试次数并更新lastGuess。
  • 添加资源关闭:在程序退出前关闭Scanner,避免资源泄漏(这是一个良好的编程习惯)。

测试示例验证

按照你给出的测试流程:

  1. 输入5 → lastGuess从0变为5,att变为1 → 提示Too Small
  2. 输入5 → 和lastGuess相同,att不变化 → 提示Too Small
  3. 输入8 → 和lastGuess(5)不同,att变为2 → 提示Too Small
  4. 输入9 → 和lastGuess(8)不同,att变为3 → 提示Too Small
  5. 输入10 → 和lastGuess(9)不同,att变为4 → 提示正确,输出4 attempts to find the correct number!

注:你提供的示例中显示5次尝试可能是笔误,按照需求逻辑,连续重复的猜测仅计一次,所以实际正确计数应为4次。

内容的提问来源于stack exchange,提问作者Jairus Matriano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:47:44