随机数字猜谜程序无法输入问题排查
Fixing Your Stuck Java Number Guessing Game
Hey there! Let's figure out why your number guessing game is getting stuck in the while loop and fix those issues right away.
The Main Issues in Your Code
There are two key problems causing the stagnation and unexpected behavior:
- Incorrect while loop condition: You're using an assignment (
gameFinished = false) instead of a comparison, which breaks the loop logic entirely. - Redundant
nextLine()call: The extrakeyboard.nextLine()at the end of the loop forces the program to wait for unnecessary input, making it seem stuck.
Fixed Full Code
Here's the corrected version of your program, with clear explanations for each change:
import java.util.Random; import java.util.Scanner; public class JavaChallenge1 { // Instance variables int number = 0; int guess = 0; boolean gameFinished = false; // Core variables Scanner keyboard = new Scanner(System.in); Random rand = new Random(); public void sampleMethod() { number = rand.nextInt(100); System.out.println("Guess the number generated."); // Changed to logical check instead of assignment while (!gameFinished) { guess = keyboard.nextInt(); // Only one nextLine() to clear the leftover newline from nextInt() keyboard.nextLine(); if (guess == number) { System.out.println("Congrats! You have guessed the number correctly."); gameFinished = true; } else { System.out.println("Bad luck. Try again."); } // Removed the redundant nextLine() that caused the input wait } // Clean up the Scanner to avoid resource leaks keyboard.close(); } // Added main method to run the program (your original code was missing this!) public static void main(String[] args) { new JavaChallenge1().sampleMethod(); } }
Breakdown of Changes
- Loop Condition Fix:
while (!gameFinished)is a clean logical check (equivalent togameFinished == false). Your original code usedgameFinished = false, which sets the variable to false every loop iteration—meaning the loop would never exit, even when you guessed correctly. - Removed Extra
nextLine(): ThenextInt()method only reads the integer value, leaving a newline character in the input buffer. The firstnextLine()clears that newline, but the second one was forcing the program to wait for another line of input, which is why it seemed stuck. - Added Main Method: Your original code didn't have an entry point to run the program, so I added a
mainmethod to instantiate the class and callsampleMethod(). - Closed the Scanner: It's good practice to close resources like
Scannerwhen you're done with them to avoid memory leaks.
How It Works Now
When you run the program:
- It generates a random number between 0 and 99.
- It prompts you to guess the number.
- For each guess you enter, it immediately tells you if you're right or wrong.
- Once you guess correctly, the loop exits and the program finishes cleanly.
内容的提问来源于stack exchange,提问作者TheNerdRed
相关产品推荐
相关产品推荐

