Help with invalid inputs for rock, paper, scissors game


#1


https://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/1/5?curriculum_id=506324b3a7dffd00020bf661

I am trying to account for an invalid input if a user enters something other than "rock" "paper" or "scissors" with my code, but my error message appears in the prompt even if I enter the correct strings of rock paper or scissors. Please help, I don't know what I'm doing wrong!


var userChoice = prompt("Do you choose rock, paper or scissors?");

if (userChoice !== "rock") {
     userChoice = prompt("Please only choose between rock, paper or scissors")}
else if (userChoice !== "scissors") {
     userChoice = prompt("Please only choose between rock, paper or scissors")}
else if (userChoice !== "paper") {
     userChoice = prompt("Please only choose between rock, paper or scissors") }


#2

Well, you need to use a single if statement here:

var userChoice = prompt("Do you choose rock, paper or scissors?");

if(userChoice !== "rock" && userChoice !== "scissors" && userChoice !== "paper") {
   // do something
}

You can also use indexOf method to check if given input is inside the array of correct values:

var userChoice = prompt("Do you choose rock, paper or scissors?");

if(["rock", "paper", "scissors"].indexOf(userChoice) === -1) {
   // do something
}

But please consider using different statement. You don't know how many times you will have to ask the user for the correct input, so maybe a while loop is a better choice?


#3

Thanks for your input! I just started learning how to code and didn't know you could do all these things. I guess I should get some more tools under my belt before I try to deviate from codecademy's lesson plans.


#4

You're very welcome :slight_smile:


Well, you have tried to solve this problem and it was a pretty good try! My advice is... keep trying. Google the indexOf method, check why I compared the result of it with -1 and try to use this method in the future :slight_smile:

There is nothing wrong in getting help here in the forums.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.