-3

When I run the program, it will never display the alert (the first if statement), even if I did guess the correct number. I could also use some help on how to loop the program 5 times, I tried a for loop with little success.


var rdmNumber = Math.random(); 
var timesNumber = rdmNumber * 10;
var theNumber = Math.round(timesNumber);
var userInput = prompt("Take a Guess (0-10)");
if(userInput === theNumber) {
    alert("You Guessed it! " + userInput + " is correct");
} else if(userInput === theNumber.toString()) {
    console.log("Higher");
} else {
    console.log("Lower");
}
console.log(theNumber);
  • `userImput` is a string, while `theNumber` is a number. See http://stackoverflow.com/q/359494/1048572 – Bergi Jan 26 '15 at 03:28
  • And a basic for loop around the `userImput` should handle your looping for 5 guesses of `theNumber` – Jason W Jan 26 '15 at 03:34

4 Answers4

1

thanks everyone, i figured out my own solution but really appreceate the feedback, this site has a great community. here is the working result

var rdmNumber = Math.random(); 
var timesNumber = rdmNumber * 10;
var theNumber = Math.round(timesNumber);
while (userInput != theNumber) {
var userInput = prompt("Take a Guess (0-10)");
if(userInput == theNumber) {
  alert("You Guessed it! " + userInput + " is correct");
}
   else if(userInput < theNumber) {
    alert("Higher");
  } 
else {
 alert("Lower");
}
}
0

As @Bergi already mentioned, userImput is a string and theNumber is an integer. What you can do is use parseInt function to convert userImput to integer like so: var userImput = parseInt(prompt("Take a Guess (0-10)")) ;

Gaurav Joseph
  • 927
  • 14
  • 25
0

I had this problem for a long time. The prompt function returns a string. you need to use parseInt() to convert that string to a number in order to do math or comparisons with it.

Here's the corrected code:

var rdmNumber = Math.random(); 
   var timesNumber = rdmNumber * 10;
   var theNumber = Math.round(timesNumber);
   var userImput = parseInt(prompt("Take a Guess (0-10)"));
   if(userImput === theNumber) {
   alert("You Guessed it! " + userImput + " is correct");
   }
   else if(userImput === theNumber) {
   console.log("Higher");
    } 
    else {
    console.log("Lower");
    }
    console.log(theNumber);
Goodword
  • 1,565
  • 19
  • 27
0

declare it in a function like this:

function guessingGame() {
    var rdmNumber = Math.random(); 
    var timesNumber = rdmNumber * 10;
    var theNumber = Math.round(timesNumber);
    var userInput = prompt("Take a Guess (0-10)");
    if(userInput === theNumber) {
        alert("You Guessed it! " + userInput + " is correct");
    } else if(userInput === theNumber.toString()) {
        console.log("Higher");
    } else {
        console.log("Lower");
    }
    console.log(theNumber);
}

and call it in your program like this:

var i=0;
while (i < 5) {
    guessingGame();
    i++;
}