在用户给出正确答案时提示结束

问题描述 投票:0回答:3

我是编码的新手,已经使用 do while 和 prompt 设置了任务。我已经创建了下面的代码。如果我输入 Gryffindor 以外的任何东西,它会说“那不是你的房子,再试一次!”所以当我再次尝试时,它没有重复,而是返回到询问他们将在哪所房子的原始提示。有人可以帮我更正吗?谢谢。

var house;

do {house = prompt("With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!");
if (prompt == 'Hufflepuff' || 'Ravenclaw' || 'Gryffindor');
    house = prompt('That is not the house for you, try again');
} while (house != 'Gryffindor'); 
house = alert ("Yes that is the house for you!")

我希望它一直重复“那不是你的房子,再试一次”,直到用户键入格兰芬多而不是返回“你将被安置在哪个房子?请输入格兰芬多、拉文克劳、赫奇帕奇或斯莱特林!”

这对某人来说是一个简单的修复程序,我仍在通过教程等自行解决。但我是编码新手,所以您能提供的任何帮助都会很棒。

谢谢

javascript do-while prompt
3个回答
1
投票
if (prompt == 'Hufflepuff' || 'Ravenclaw' || 'Gryffindor')

如果你想将变量与不同的值进行比较,你需要像这样重复比较

if (prompt == 'Hufflepuff' || prompt == 'Ravenclaw' || prompt == 'Gryffindor')

或者,您可以使用像这样的 switch 语句

switch (prompt) {
    case 'Hufflepuff':
    case 'Ravenclaw':
    case 'Gryffindor':
        // prompt is either Hufflepuff | Ravenclaw | Gryffindor
        break;
    default:
        // else
        break;
}

1
投票

更简单的方法是不使用

do ... while
循环。无论如何使用它的控制流有点混乱,所以这要容易得多:只需使用
while
循环本身!

let house = prompt( "With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!");
 
// Just repeat the question until your value is equal to Gryffindor
while( house !== "Gryffindor" ) house = prompt( "That is not the house for you, try again" );

alert( "Yes that is the house for you!" )

如果您坚持使用

do ... while
循环(注意:不推荐),解决方案是不要有if条件——您的
while
本质上就是这样。只要您的
while
条件中的代码评估为真,它就会进行另一轮
do

let house = prompt( "With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!");
 
// It's best _not_ to go to your do..while at all if your condition is met
// The issue, obviously, is that you have to repeat the condition twice!
// That's clearly against the "Don't Repeat Yourself" principle.

if( house !== "Gryffindor" ) do {
   house = prompt( "That is not the house for you, try again" );
} while( house !== "Gryffindor" )

alert( "Yes that is the house for you!" )

为什么不推荐?因为

do ... while
循环非常混乱,所以您的
condition
仅在大量代码之后列出,与大多数情况下的情况相反(如
if
switch
)。我从未在任何地方的生产环境中看到过
do ... while
代码,最好保持这种状态。


0
投票

如果给出正确答案,您可以使用无限循环

while(true)
break
break
将退出最近的循环。

do {
  const house = prompt("With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!");
  if(house == 'Gryffindor')
  {
    break;
  }
  alert('That is not the house for you, try again');
} while (true);
alert("Yes that is the house for you!")

然而,这缺乏其他答案之一的清晰度。把它留在这里,因为它是从你的代码到有效的东西的自然进展 - 但如果你想要 better 代码,请选择其他答案!

© www.soinside.com 2019 - 2024. All rights reserved.