1

Hello I have a simple script:

var play = true;
var correct = false;
var number = 0;
var guess = 0;
while (play) {
  // random number between 1 and 10.
  number = Math.floor(Math.random() * 10 - 1);
  if (number == 0) number = 1;


  while (!correct) {
    guess = window.prompt("What is the number?");

    if (guess < number) {
      alert("Guess higher ;)");
    } else if (guess > number) {
      alert("Guess lower ;)");
    } else if (guess == number) {
      correct = true;
      alert("You got it!");
    }
  }

  if (window.prompt("Do you want another game?", "yes") != "yes") {
    play = false;
  }
}

When I get the number right and prompted to "Do you want another game?" and enter "yes", the program redisplays and stuck at "Do you want another game?".

1 Answer 1

2

You need to reset the state of correct on every play loop:

let play = true;

while (play) {
  let number = Math.floor(Math.random() * 10 + 1);
  let guess = 0;
  let correct = false;

  while (!correct) {
    guess = window.prompt("What is the number?");

    if (guess < number) {
      alert("Guess higher ;)");
    } else if (guess > number) {
      alert("Guess lower ;)");
    } else if (guess == number) {
      correct = true;
      alert("You got it!");
    }
  }

  if (window.prompt("Do you want another game?", "yes") != "yes") {
    play = false;
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.