Prompting user to enter correct input stores the first (incorrect) input (lesson 9)


#1

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

I made an input check that if the user enters something with more than 10 chars they needs to go back and enter correct values. When I tested this with "werw5434543646456456456" I got the prompt "Enter correct options!", then entered "rock". But my console.log printed:

human werw5434543646456456456 versus computer paper

And nobody wins. Why is this happening? How do I store the most recently input value?

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

if (userChoice.length > 10) {
    prompt ("Enter correct options!");
};

var computerChoice = Math.random();
if (computerChoice < 0.34) {
	computerChoice = "rock";
} else if(computerChoice <= 0.67) {
	computerChoice = "paper";
} else {
	computerChoice = "scissors";
}

var compare = function(choice1,choice2)

{
    if(choice1===choice2)
    {
        var userChoice = prompt ("The result is a tie! Enter again.");
        
    }
    else if(choice1==="rock")
        {if(choice2==="scissors")
        {
        return "human rock wins";
         }
        else
        {return "computer paper wins"}
        }
    else if(choice1==="paper")
        {if(choice2==="rock"){
            return "human paper wins"}
        else{
            return "computer scissors wins";}}
    else if(choice1==="scissors"){
        if(choice2==="rock"){
            return "computer rock wins";
        }
        else {
            return "human scissors wins";
        }
        
    }
};
console.log("human" + userChoice + " versus computer " + computerChoice);
compare(userChoice, computerChoice);

similary, if i enter rock, paper, or scissors first and it's a tie, then enter something else, I get human rock versus computer rock, but no one wins. If I enter jibberish w more than 10 chars I am not prompted to enter a correct value.


#2

userChoice still holds the first prompt, you don't store the result of the second prompt in userChoice.


#3

yes i can see that, so how does one fix that?


#4

the same way you did here:

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

store the result of prompt in userChoice, you can do the same inside your if clause, just set userChoice to hold the result of the prompt, this will update the variable


#5

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