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
Bob Puccini
7,011 PointsJavascript code is bugged, but I don't know why!
Hi guys, I'm a begginer at Javascript. I made a little guessing game when you try to guess a random number generated between 1 and 6. The program works only sometimes. Sometimes, I'll guess 6 as the number, and it will tell me I'm wrong, yet till me the correct number was 6.
My code:
function getRandomNumber () {
var randomNumber = Math.floor( Math.random() * 6) + 1;
return randomNumber;
}
var guess1 = parseInt(prompt("Guess the number I'm thinking about. It's between 1 and 6!"));
if ( guess1 === getRandomNumber() ) {
document.write("<p>Wow! That correct!</p>");
} else {
document.write("<p>Sorry, but that's incorrect. The correct number was " + getRandomNumber() + ".</p>");
}
Please help.
eck
43,038 PointsYour Markdown formatting for you code was nearly correct, you just need to give the first three ticks a line of space away from the preceding paragraph.
2 Answers
eck
43,038 PointsStoring the result of getRandomNumber() in a variable should fix this. The problem is that you are calling the function twice, which generates a new random number twice. Here is an example of what should work:
function getRandomNumber () {
var randomNumber = Math.floor( Math.random() * 6) + 1;
return randomNumber;
}
var guess1 = parseInt(prompt("Guess the number I'm thinking about. It's between 1 and 6!"));
var answer = getRandomNumber();
if ( guess1 === answer ) {
document.write("<p>Wow! That correct!</p>");
} else {
document.write("<p>Sorry, but that's incorrect. The correct number was " + answer + ".</p>");
}
Bob Puccini
7,011 PointsBut what if I want to let the user guess twice, and I don't want to use the same number again? Edit: Thanks!
eck
43,038 PointsThere are different ways you could do this, but if you wanted to reuse the answer variable, you could just reassign its value with answer = getRandomNumber();
This changes the value of answer to a new random number.
Bob Puccini
7,011 PointsAlright. But do you have any idea what might be causing the bug?
Bob Puccini
7,011 PointsBob Puccini
7,011 PointsMy code: