Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 884
Finn E Avatar asked Apr 17 '26 20:04

Finn E


2 Answers

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()
like image 64
prasanth Avatar answered Apr 19 '26 09:04

prasanth


You can use a simple do ... while structure.

let next = false
do {
  let opt = prompt("Do you want to TALK or LOOK?").toUpperCase();
  next = false
  switch (opt) {
    case 'TALK':
    case 'LOOK':
      break;
    default:
      next = true
  }
} while (next)
like image 43
Diego Avatar answered Apr 19 '26 10:04

Diego



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!