Finn E Finn E - 3 years ago 47
Javascript Question

Repeat switch statement until it has a valid answer

I'm a beginner trying to make a text adventure game in JavaScript, and I need to repeat a switch statement until the user enters a valid answer:



opts = prompt("Do you want to TALK or LOOK?").toUpperCase();

switch(opts) {
case "TALK":
mes = "Is anyone in charge here?";
speech = "Our leader is in the big building.";
talkNot();
break;
case "LOOK":
window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street.");
break;
default:
window.alert("That's not an option.");
}





Any answers would be super helpful - thanks!

Answer Source

Wrap the code with some function and callback the function in default statement

function run(){
opts = prompt("Do you want to TALK or LOOK?").toUpperCase();

switch(opts) {
  case "TALK":
    mes = "Is anyone in charge here?";
    speech = "Our leader is in the big building.";
    console.log('talk')
    //talkNot();
    break;
  case "LOOK":
    window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street.");
    break;
  default:
    window.alert("That's not an option.");
    run() //callback 
}
}

run()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download