简体   繁体   English

在while循环内编写提示

[英]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. 我希望代码仅在用户输入石头,纸张或剪刀的情况下才继续,但是尽管我在while循环中通过了条件,但第二次重新输入任何内容后,代码似乎仍继续。 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". 例如,如果我键入“ asdf”,它将要求我重新输入,但是如果我再次执行“ asdf”,它将退出while循环并注销“ 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. 因此,如果用户重新输入多次,则返回false或退出系统。

  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. 将userChoice分配给“ paper”,“ scissors”或“ rock”的值后,如果不更改,其值将保持不变,因此while循环不会重新开始。

Try after you run whatever code comes after the while loop adding something like this. 在运行类似while循环之后添加的代码后,尝试运行。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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