Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Making Decisions with Conditional Statements Build a Random Number Guessing Game

looping this script and validating input?

Hello

var randomNumber =Math.floor(Math.random() *6) + 1; var guess = prompt('I am thinking of a number between 1 and 6. What is it?'); if (parseInt(guess) === randomNumber) {

document.write('You guessed the number!'); }else{ document.write('Sorry. The number was ' + randomNumber + '. '); }

How would you get this script to loop? I was trying to figure out how to get to run the script again by prompting user for yes or know then repeating but nothing is working, also wanted to know how you would go about validating the user's input so that it was a number between 0-6 and came back with an alert if wrong.

Thanks.

3 Answers

Zack Jackson
Zack Jackson
30,220 Points

This conditional statement is essentially a binary check. The user inputs their guess and it is either correct (=== randomNumber) or it is not. If it is, they win, if it is not, the conditional ends and tells them what the randomNumber was thus ending the game.

You need the game to continue until the correct number is guessed. I would use a while loop to do this. Check out this codepen: https://codepen.io/anon/pen/zmqBpb

You can add a conditional in there to prompt the player to continue or expand on this. Maybe create a variable for a set number of guesses that the user has available and end the game after they run out of chances.

You can add a check with an if statement to validate the input as well. For instance, if you were to do the following:

if (parseInt(guess) > 0 && parseInt(guess) <= 6) { while loop } else { error message}

Thank you that is really helpful. I will study and put that into practise I'm future scripts.

Thanks again

Junet Ismail
Junet Ismail
3,563 Points

Anyone interested in doing this . This is my own take on the task with a loop that keeps asking until the right number is entered. Make sure you have the console open to see the random number.

https://w.trhou.se/ryjqwq7fkz