What if a user makes an inappropriate choice like 'dog'? How can we extend the function to handle that?


#1


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

    
    
var computerChoice = Math.random();
if (computerChoice < 0.34) {
	computerChoice = "rock";
} else if(computerChoice <= 0.67) {
	computerChoice = "paper";
} else {
	computerChoice = "scissors";
} console.log("user: " + userChoice);
console.log("Computer: " + computerChoice);

var compare=function(choice1,choice2){
    if(choice1===choice2){
        return "The result is a tie!" 
        }
        else if(choice1==="rock"){
            if(choice2==="scissors"){
                return "rockwins"
                
                }
                else{
                    return "paperwins"
                    
                    }
            
            }
            else if(choice1==="paper"){
            if(choice2==="rock"){
                return "paperwins"
                
                }
                else{
                    return "scissorswins"
                }
            }
            else if(choice1==="scissors"){
            if(choice2==="rock"){
                return "rockwins"
                
                }
                else{
                    return "scissorswins"
                }
            }
    
    }
    
    compare(userChoice,computerChoice);


#2

add an "else" in parallel with the first "if(choice1 === choice2)" that returns "That is not a valid input!" The logic there is that if its not any of the choices, paper, rock, or scissors then it would be an inappropriate choice.

If you want to see my code let me know.


#3

@fordafuture111 What do you mean by "in parallel"?


#4

So with an if statement there is an else statement so just add an else statement at the end

The idea here is that IF the user does not input rocks, paper or scissors then just return "this is not a valid input"


#5

You can use a while loop to solve this problem.
The while loop loops through a block of code as long as a specified condition is true.
I know this while loop isn't treated in the JavaScript course yet but it's the easiest way I know to solve the problem. (also: || means 'or').
I hope this helps :slight_smile:

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

ps. Place the while loop directly under the line: var userChoice = prompt("Do you choose rock, paper or scissors?");


9.01 - How to handle invalid input?
#6

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