Boo Boo
Boo Boo

Reputation: 80

How come my guess the number game in JavaScript isn't working?

Whenever I enter a number it says the number is too low even if the number is way greater than the other number. When I enter zero or don't enter anything at all it says your number was too low. I don't get it i have looked over my code a bunch of times, but I still haven't found any problems.

Here is my code:

var answer = prompt("Guess a number between 1 and 100");
var number = confirm(Math.round(Math.random()*100));

if (number === answer) {
    confirm("You win!");
} else if(number < answer){
    confirm("Your number was too low!");
} else if (number > answer) {
    confirm("Your number was too high!");
}   

Upvotes: 1

Views: 122

Answers (4)

bnjc
bnjc

Reputation: 56

Try converting answer to an integer value first using the parseInt() function;

var answer = parseInt(prompt("..."));

Upvotes: 2

user7396942
user7396942

Reputation:

the variables answer and number is not have the same kind, for convert use parseInt in the var answer, see my answer:

var answer = prompt("Guess a number between 1 and 100");
var number = confirm(Math.round(Math.random()*100));
answer=parseInt(answer);
if (number === answer) {
    confirm("You win!");
} else if(number < answer){
    confirm("Your number was too low!");
} else if (number > answer) {
    confirm("Your number was too high!");
}

Upvotes: 1

bur&#230;quete
bur&#230;quete

Reputation: 14688

var answer = prompt("Guess a number between 1 and 100");
var ai_nswer = Math.round(Math.random() * 100);
var number = confirm(ai_nswer);

if (ai_nswer == answer) {
    confirm("You win!");
} else if(ai_nswer > answer){
    confirm("Your number was too low!");
} else if (ai_nswer < answer) {
    confirm("Your number was too high!");
}  

Apart from confirm method you are using was not proper, the logic was also problematic. Your if conditions were wrong for high/low. You should store the value of your random answer in a temp value, and then confirm it, since confirm returns a boolean value, not the input value.

Upvotes: 1

Tony Dinh
Tony Dinh

Reputation: 6726

The confirm function returns a boolean (true or false), so the number variable in the line below actually hold a boolean value.

var number = confirm(Math.round(Math.random()*100));

And that messed up your logic.

Simply change it to:

var number = Math.round(Math.random()*100);
confirm(number);

Another notice

prompt("Guess a number between 1 and 100"); returns a string, so to be 100% clear, you should cast the value to number:

var answer = Number(prompt("Guess a number between 1 and 100"));

Upvotes: 1

Related Questions