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

Node.js数字猜谜游戏while循环逻辑异常求助

Fixing Your Node.js Number Guessing Game Loop

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
    The readlineSync.question() method returns a string by default. If your random number ranNum is a numeric value, comparing a string guess to a number will always evaluate to false (even if the characters match, like "5" vs 5). You need to convert the user's input to a number using parseInt() or Number().

  • Variable name mismatch
    In your prompt, you're referencing a variable number but defined maxNum earlier. That's either a typo or an undefined variable error, which will break your code entirely. Replace number with maxNum to 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 the readlineSync.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:31:45