Node.js数字猜谜游戏while循环逻辑异常求助
Hey there! Let's figure out why your while loop isn't repeating the prompt when the user guesses wrong. From the code snippet you shared, there are a couple of key issues throwing off the logic—let's break them down and fix them:
Common Issues & Fixes
Input is stored as a string, not a number
ThereadlineSync.question()method returns a string by default. If your random numberranNumis a numeric value, comparing a string guess to a number will always evaluate tofalse(even if the characters match, like"5"vs5). You need to convert the user's input to a number usingparseInt()orNumber().Variable name mismatch
In your prompt, you're referencing a variablenumberbut definedmaxNumearlier. That's either a typo or an undefined variable error, which will break your code entirely. ReplacenumberwithmaxNumto match your variable declaration.Loop isn't re-prompting for new guesses
If you're only capturing the user's guess once outside the loop, the loop will keep checking the same stale value instead of asking for a new guess each time. You need to move thereadlineSync.question()call inside the while loop.
Corrected Code Example
const readlineSync = require('readline-sync'); // Get user's name and max number first const name = readlineSync.question("What's your name? "); const maxNum = parseInt(readlineSync.question(`${name}, choose a maximum number (e.g., 100):\n`)); // Generate random number between 0 and maxNum (inclusive) const ranNum = Math.floor(Math.random() * (maxNum + 1)); let userGuess; while (true) { // Get new guess each loop iteration, convert to number userGuess = parseInt(readlineSync.question(`Please guess a number between 0 and ${maxNum}:\n`)); // Validate input first if (isNaN(userGuess) || userGuess < 0 || userGuess > maxNum) { console.log(`Oops! Please enter a valid number between 0 and ${maxNum}.`); continue; // Skip to next loop iteration if input is bad } // Check guess against random number if (userGuess === ranNum) { console.log(`Great job, ${name}! You guessed the right number!`); break; // Exit loop when guess is correct } else if (userGuess > ranNum) { console.log("Too high! Try again."); } else { console.log("Too low! Try again."); } }
Key Improvements in This Code
- Converts all user input to numbers with
parseInt()to ensure proper comparisons. - Moves the guess prompt inside the loop so the user gets asked again after every wrong guess.
- Adds input validation to handle non-numeric entries or guesses outside the 0-to-maxNum range.
- Uses template literals (
`${variable}`) for cleaner, easier-to-read prompt text.
内容的提问来源于stack exchange,提问作者Jayyy

