Wrong input ? Exit code!


#1

Hello!
I'm trying to write an additional code which will prevent user to input anything else except "paper, rock or scissors".
So i tought i coud write it this way:

If userChoice is NOT paper OR rock OR scissors
exit code, write error message

but it seems that logical operators aren't working here or am I
missing something or doing wrong? Because if i do it with only "paper" ,
for example(if(userChoice!== "paper"){error},
it works.
Any suggestions? Thanks in advance!

if(userChoice !== "paper" || userChoice !== "scissors" || userChoice !== "rock")
{
throw new Error("Please type in paper, rock or scissors!");


#2

|| is the wrong operator. If you enter something valid you will get:

false or true or true

which is true. While it should be false (since the user made a valid choice, you don't want if to validate to true). if the user enters something invalid you get:

true or true or true

which is true. We should use and, because then for a valid input we get:

false && true && true

which is false, and for invalid input:

true && true && true

which is true


#3

Wow, thank you very much it works perfect now !


#4

if you already use code which isn't taught yet:

throw new Error

why not simply use a do-while loop?


#5

var userChoice;
do
{
userChoice = prompt("Do you choose rock, paper or scissors?");
}
while(userChoice!== "paper" && userChoice!== "scissors" && userChoice!== "rock");

Thanks for an idea!


#6

you don't even need ^ that line, you assign in the loop, so that is fine


#7

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