I am new to coding and have been set a task using a do while and prompt. I have created the code below. If I put anything other than Gryffindor it states ‘That is not the house for you, try again!’ so when I try again it, instead of repeating that, it returns to the original prompt of asking which house they will be in. Could someone help me correct it? Thank you.
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!")
I want it to keep repeating ‘That is not the house for you, try again’ until the user types Gryffindor rather than go back to "With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!"
This will be an easy fix for someone and I am still working on it myself with tutorials etc. but I am new to coding so any help you could give would be great.
Thanks
3
Answers
You could make use of an infinite loop
while(true)
andbreak
if the right answer is given.break
will exit out of the nearest loop.However this lacks the clarity of one of the other answers. Leaving this here as it’s a natural progression from your code to something that works – but if you want the better code go with the other answer!
A simpler way would be to not use the
do ... while
loop. It’s a bit of a confusing control flow to use anyway, so this is a lot easier: just use awhile
loop itself!If you insist on a
do ... while
loop (note: not recommended), the solution is to not have an if condition – yourwhile
is essentially that. As long as the code in yourwhile
condition evaluates to true, it will do another round ofdo
:Why is it not recommended? Because a
do ... while
loop is pretty confusing, yourcondition
is only listed after a lot of code, inverse to how it is in most conditions (likeif
orswitch
). I have never seen ado ... while
code in production anywhere, and it’s best to keep it that way.If you want to compare variable to different values you will need to repeat the comparison like
Alternatively, you can use a switch statement like