Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Christopher Lindor
Christopher Lindor
2,851 Points

Ending on wrong statement

Hello when I guess the correct answer on the first try the program doesn't end on the true statement instead it ends as if the guess was false. I added a console log to display the number so i can guess it correctly but when i do the program ends and says i got the question wrong

var correctGuess = false;

//Asking for starting information name and generating random number also asking for user input.;
var userName = prompt('lets test your luck, but first let me know your name');
var randomNumber = parseInt(Math.floor(Math.random() * 6) + 1);
console.log(randomNumber);
var guess = prompt('I am thinking of a number between 1 and 6. Try and guess what it is');


if (guess === randomNumber) {
    correctGuess = true;
} else if (guess < randomNumber) {
    var guessMore = parseInt(prompt(' Try agian. The number I am thinking is more than ' + guess));
    if (guessMore === randomNumber) {
        correctGuess = true;
    }

} else if (guess > randomNumber) {
    var guessLess = parseInt(prompt('<p> Try agian. The number I am thinking is less than ' + guess));
    if (guessLess === randomNumber) {
        correctGuess = true;
    }
}

if (correctGuess) {
    document.write('<p> Wow ' + userName + ' you are really lucky good guess</p>');
} else {
    document.write('<p>I\'m sorry ' + userName + ' the right number was ' + randomNumber + '</p>');
}

1 Answer

Christopher Lindor
Christopher Lindor
2,851 Points

I feel so stupid I found my error I was converting the number that was already a number instead of the string that the user inputs into a number. once I moved the parseInt to the guess value the program ran correctly.