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 JavaScript Basics (Retired) Working With Numbers The Random Challenge

The Random Challenge. Pros, please critique.

My solution to the random challenge was to continually ask the user for an integer until one was given. Is it possible to do this without a nested loop?

Ignore the PHP variable naming convention.

var $userLowNumber; //input from user for the low value.
var $userHighNumber; //input from user for the high value.
do {
    $userLowNumber = parseInt(prompt("Please enter a low value."));
    if (isNaN($userLowNumber))
        continue;
    do {
        $userHighNumber = parseInt(prompt("Please enter a high value."));
    } while (isNaN($userHighNumber))
} while (isNaN($userLowNumber));

alert("Your random number is " + (Math.floor(Math.random() * ($userHighNumber - $userLowNumber) + 1 ) + $userLowNumber));

1 Answer

I believe you can just do it like this, no need for do..while:

var $userLowNumber; //input from user for the low value.
var $userHighNumber; //input from user for the high value.

while (isNaN($userLowNumber)) {
    $userLowNumber = parseInt(prompt("Please enter a low value."));
}

while (isNaN($userHighNumber)) {
    $userHighNumber = parseInt(prompt("Please enter a high value."));
}

alert("Your random number is " + (Math.floor(Math.random() * ($userHighNumber - $userLowNumber) + 1 ) + $userLowNumber));

Although, you're going to run into a problem with parseInt: if someone enters 1.9, parseInt will simply return 1 as the integer.

And what if the high value is lower than the low value?

I'm ok with a decimal getting truncated. But I like your question. Now to think what's the easiest way to check if the low value is indeed lower the high value and repeat the high value loop.

Maybe something like...

var $userLowNumber; //input from user for the low value.
var $userHighNumber; //input from user for the high value.

while (isNaN($userLowNumber)) {
    $userLowNumber = parseInt(prompt("Please enter a low value."));
}

while (isNaN($userHighNumber) || $userHighNumber <= $userLowNumber ) {
    $userHighNumber = parseInt(prompt("Please enter a high value."));

} 

alert("Your random number is " + (Math.floor(Math.random() * ($userHighNumber - $userLowNumber) + 1 ) + $userLowNumber));