Whats wrong with my code?


#1

https://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/0/4?curriculum_id=506324b3a7dffd00020bf661#

instead of simply putting out one value, it keeps putting out multiple choices such as if number is .17 and i get rock and scissors. Im at a complete lost for why this is happening, please help!

var userChoice = prompt("Do you choose rock, paper or scissors?")
var computerChoice = math.random()
console.log(computerChoice)
if (computerChoice <= .33)
{
    computerChoice = "rock";
    console.log(computerChoice);
}
else if (computerChoice > .33 && computerChoice < .67)
{
    computerChoice = "paper";
    console.log(computerChoice);
}
else (computerChoice >= .67)
{
    computerChoice = "scissors";
    console.log(computerChoice)
}

#2

For one I think your "math.random()" needs to be "Math.random()". Also, you are logging the computer choice outside the if statement and inside the if statements. If one of those is true, then it will log twice.

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

console.log(computerChoice);

if (computerChoice < 0.33){
    computerChoice = "rock";
}
else if(computerChoice > 0.34 && computerChoice < 0.66){
    computerChoice = "paper";
}
else
{
    computerChoice = "scissors";
}

#3

i"m logging it twice on purpose, the first time to see what number i get and the second to see what result it corresponds to. also i do have it set to Math.random() I don't know why it copied like that. I've changed my code to look like this but its still not working right, it just prints scissors

var userChoice = prompt("Do you choose rock, paper or scissors?")
var computerChoice = Math.random()
console.log(computerChoice)
if (computerChoice <= .33)
{
    computerChoice = "rock";
}
else if (computerChoice > .33 && computerChoice < .67)
{
    computerChoice = "paper";
}
else (computerChoice >= .67)
{
    computerChoice = "scissors";
}
console.log(computerChoice)

#4

Else statements don't take a condition. They just execute code blocks when prior if/else if conditions haven't been met.


#5

Another thing I just noticed is that you're trying to take a condition for your else. Else takes no condition since it just 'defaults' to that if there is no argument in the if that is satisfied.

if(){

}
else if (){

}
else
{

}

#6

Thanks a lot to both of you, that was super helpful!


#7

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