带用户输入的随机数生成器代码运行异常求助
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
ifstatement, which works if you guess right on the first try, but the two separatewhileloops 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
whileloop: 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
attemptCountevery time the user enters a guess—no more relying on a finalifstatement to catch the first guess. This eliminates any off-by-one errors. - Better readability: Renamed variables to be more descriptive (
targetNumberinstead ofnumber,userGuessinstead ofattempt), 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

