Cannot see the error in my code


#1

See my code below. It seems to run fine, giving output, but I am getting a message saying "oops...." My code is pasted below, please paste and run to see the message.

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("Computer: " + computerChoice);

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";
}
if (choice1 === "scissors")
{
if (choice2 === "rock")
return "rock wins";
}
else if (choice2 === "paper")
{
return "scissors wins";
}

};
compare(userChoice, computerChoice);


#2

Take a look at your code with proper formatting. Please note my comment! :smile:

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("Computer: " + computerChoice);

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 {				// <-- this else is misplaced :)
        return "scissors wins";
    }
    if (choice1 === "scissors") {
        if (choice2 === "rock")
            return "rock wins";
    } else if (choice2 === "paper") {
        return "scissors wins";
    }

};
compare(userChoice, computerChoice);

#3

Ah, ok! Yes, now it works, thanks!


#4

You're very welcome! :panda_face:


#5

Thank you so much for your input and your code works well, but I have a question.

How come you use math.random in your solution when in reality these are by no means covered in the course so far?

I'd appreciate your answer,

Lily


#6

Usage of Math.random() is described in the third lesson of this section -> https://www.codecademy.com/en/courses/javascript-beginner-en-Bthev-mskY8/0/3,