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

带用户输入的随机数生成器代码运行异常求助

Fixing Your Guess-the-Number Program: Counting Issues & Optimization

Hey BellaCarol! Let's walk through your program to fix the guess count problem and clean up the code for better readability.

First, Let's Diagnose the Counting Quirk

Looking at your current code, the count mostly works, but the logic is convoluted, which can lead to confusion (and maybe the off-by-one errors you're seeing). Here's why:

  • Your first guess isn't counted until the final if statement, which works if you guess right on the first try, but the two separate while loops make it easy to lose track of how attempts are tallied.
  • The final output has a small grammar issue (". attempt" should be " attempts").

Here's the Optimized Version of Your Code

Let's rewrite it with a single loop for cleaner logic and more accurate counting:

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

public class GuessTheNumber {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random random = new Random();
        
        // Generate target number between 1-100
        int targetNumber = random.nextInt(100) + 1;
        int userGuess = 0;
        int attemptCount = 0;
        
        System.out.println("Welcome to Guess the Number! I'm thinking of a number between 1 and 100.");
        
        // Single loop runs until user guesses correctly
        while (userGuess != targetNumber) {
            System.out.print("Enter your guess: ");
            userGuess = input.nextInt();
            attemptCount++; // Increment count every time a guess is made
            
            if (userGuess < targetNumber) {
                System.out.println("Too low! Guess a bigger number.");
            } else if (userGuess > targetNumber) {
                System.out.println("Too high! Guess a smaller number.");
            }
        }
        
        // When loop exits, user guessed correctly
        System.out.println("Congratulations! You guessed the number in " + attemptCount + " attempts!");
        input.close(); // Don't forget to close the scanner
    }
}

Key Improvements Explained

  • Single while loop: Instead of two separate loops for "too low" and "too high", we use one loop that continues until the guess matches the target. This makes the logic much easier to follow.
  • Straightforward counting: We increment attemptCount every time the user enters a guess—no more relying on a final if statement to catch the first guess. This eliminates any off-by-one errors.
  • Better readability: Renamed variables to be more descriptive (targetNumber instead of number, userGuess instead of attempt), added comments, and fixed the output grammar.
  • Resource cleanup: Added input.close() to properly close the Scanner (good practice to avoid resource leaks).

Why Your Original Counting Might Have Seemed Off

In your original code, the first guess was only counted if it was correct (via the final counter++). For subsequent guesses, you counted them in the loops, then added 1 at the end. This works, but it's easy to lose track of why the count is being incremented where—leading to confusion when debugging. The optimized version makes it crystal clear: every input = one attempt.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:42:00