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) Creating Reusable Code with Functions Random Number Challenge Solution

nick schubert
nick schubert
3,535 Points

I can't figure out why the input isn't working.

I used two variables as the parameters for the random generated number. However, I discovered that these paremeters can't be used using Math.random() and will be ignored.

Now I'm simply clueless as to how to fix this issue. Help will be greatly appreciated!

This is the code I used:

//These variables store the input of the user which can then be used by the randomNrGenerator function. If the user doesn't enter a number an alert will be prompted. var one = prompt("Enter a number."); if (isNaN(one)) { alert("That's not a number."); one = prompt("Enter a number, please."); } else { parseInt(one); console.log("First number: " + one); } var two = prompt("Enter a higher number than the previous one."); if (isNaN(two)) { alert("That's not a number."); one = prompt("Enter a number, please."); } else { parseInt(two); console.log("Second number: " + two); }

// This function generates a random number using the input of the user. function randomNrGenerator(one, two) { return Math.floor(Math.random() * ( two - one + 1 )) + one; // I think the variables aren't being used and I still end up with a random generated number. } console.log("random number using " + one + " and " + two + ": " + randomNrGenerator( one , two ) + " ...wtf?" );

1 Answer

David Perkins
David Perkins
9,607 Points

Try this. It seems to work for me after a number of test cases...

var min = prompt('Enter a low number.');
var max = prompt('Enter a high number.');

if (isNaN(min)) {
  alert("That's not a number.");
  min = prompt('Enter a low number, please.');
} else {
  var min = parseInt(min);
  console.log('Low number: ' + min);
}

if (isNaN(max)) {
  alert("That's not a number.");
  min = prompt('Enter a high number, please.');
} else {
  var max = parseInt(max);
  console.log('High number: ' + max);
}

function randomNrGenerator(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

console.log(
  'Random number between ' +
    min +
    ' and ' +
    max +
    ': ' +
    randomNrGenerator(min, max)
);