# Problem lesson 9

#1

Hi, how could write my code so I ask the user to change his input UNTIL he choose rock, scissors or papers. In the following code he could still choose something else after the prompt.

Thanks !

// define choice

``````var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();

// if user doesn't choose rock, paper, or scissors value

if (userChoice!= "rock" && userChoice!="paper" && userChoice!="scissors") {
userChoice = prompt ("NOT VALID, please choose rock, paper, or scissors.");
}

// define computer choice

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

// define comparative function

var compare = function (choice1,choice2) {

if (choice1===choice2) {
return  "The result is a tie!";
}

else if (choice1==="rock") {

if (choice2==="scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}

else if(choice1==="paper") {

if (choice2==="rock") {
return "paper wins";
}
else{
return "scissors wins";
}
}

else if (choice1==="scissors") {
if (choice2==="paper") {
return "scissors wins";
}
else {
return "rock wins";
}
}

}

compare(userChoice,computerChoice)``````

#2

You can't achieve this with a if statement, if statement only checks once. You need a loop (i might get ahead of the exercises at this point), for this situation, a do while loop would be ideal. Why? Well, a do while loop execute at least once (which is good, we need to prompt the user for input at least once) and then until the user input is valid, sound good?

so, some general sytnax:

``````do {
/* prompt user for his choice */
} while ( /* check if user input is valid */ )``````

so, now we can fill in our data:

``````do {
userChoice = prompt ("Please enter rock, paper or scissors");
} while (userChoice!= "rock" && userChoice!="paper" && userChoice!="scissors")``````

now, if you don't completely got the hang if this loop, don't worry, this will be explained in later lessons.

#3

Thank you for the help!!

#4

Hi, sorry to eavesdrop. Where should the do while loop be placed? Would it be before the if statement starts? Thanks so much. - Efraim

#5

well, maisonk did already have a validation:

``````// if user doesn't choose rock, paper, or scissors value

if (userChoice!= "rock" && userChoice!="paper" && userChoice!="scissors") {
userChoice = prompt ("NOT VALID, please choose rock, paper, or scissors.");
}``````

i suggested an improvement. So, i would place the while loop where the if statement was