简体   繁体   中英

Writing a prompt inside a while-loop

I want the code to continue, only if the user inputs rock, paper or scissors, but it seems to continue after I re-enter any input the second time, despite it passing the condition in the while loop. For example, if I type "asdf" it will ask me to re-enter the input, but then if I do "asdf" again, it exits the while-loop and logs out "asdf". I want it to keep prompting the user until they enter "rock", "paper" or "scissors"

var userChoice = prompt("Enter rock, paper, or scissors", "rock").toLowerCase();


while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors" ) {
  userChoice = prompt("renter Please");
}

console.log(userChoice);

So if the user reenters more than one time you return false or exit the system.

  var userChoice = prompt("Enter rock, paper, or scissors").toLowerCase(); while (userChoice != "rock" && userChoice != "paper" && userChoice != "scissors") { userChoice = prompt("renter Please"); } console.log(userChoice) 

As soon as you assign userChoice to a value of "paper" "scissors" or "rock" its value will stay that way if not changed so the while loop wont restart.

Try after you run whatever code comes after the while loop adding something like this.

while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors" ) {
  userChoice = prompt("renter Please");
}

console.log(userChoice);

userChoice = 0;

This will only work however if your code is nested in another loop

loop{
    var userChoice = prompt("Enter rock, paper, or scissors", "rock").toLowerCase();

    var userChoice = prompt("Enter rock, paper, or scissors", "rock").toLowerCase();


    while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors" ) {
      userChoice = prompt("renter Please");
    }

    console.log(userChoice);
    userChoice = 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM