Ask coding questions

← Back to all posts
How do I add a "Invalid Argument, Please Try Again" Commands to my code?
Hamburgr (18)

In my game, I am trying to add a command that if the user doesn't write a valid argument, it will replay the code. Currently, for the main startup for the code, it has two options attack and run. I am trying to make it so if the user puts in an argument that is not one of those two, it will say Invalid Argument, Please enter a valid option. Can anyone help me with this?

@Coder100 If you haven't noticed, this is clearly a remake of one of your game jam entries in a different language. This was made solely for learning purposes.

Answered by Coder100 (16759) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (16759)

Ok, so I would recommend you doing something like:

console.log('A ' + enemyType + ' approaches!');
console.log('1. Attack')
console.log('2. Run')
var userOption = prompt('What would you like to do?: ');

switch (userOption) {
  case "run":
    // code
    break;
  case "attack":
    // code
    break;

   default:
    console.log("invalid");
    break;
}

You can read up on it here

Coder100 (16759)

and no I am honored that people take inspiration :)

Coder100 (16759)

ok looking on to it

idrgplayer (128)

@idrgplayer if yes then pls mark my answer correct. :)

RYANTADIPARTHI (6006)

Put an else

like this:

else {
  document.write("not valid")
}
RYANTADIPARTHI (6006)

@Hamburgr put the else with an if statement.