Manievat - 6 months ago 19
HTML Question

# What's wrong with this random number guessing game?

I made a random number guessing game in which you can determine the maximum value and the minimum value. I checked my entire code twice but can't seem to find a solution to why it won't work. I made this script linked to a HTML file that explains the

document.getElementById("randNum").innerHTML
part.
I also want to say I am very new to coding so I might've overlooked something simple. Anyways, here's my code.

var max = prompt("Max guessing number?");

if (max <= 2) {
document.getElementById("randNum").innerHTML = "Invalid entry";
} else {

var min = prompt("What's the smallest number you can guess?");
if (min >= (max - 1) || min <= 0) {
document.getElementById("randNum").innerHTML = "Invalid entry";

} else {

number = Math.floor(Math.random() * (max - min + 1) + min);

if (guess > max || guess < min) {

document.getElementById("randNum").innerHTML = "Invalid entry";

} else if (guess == number) {

document.getElementById("randNum").innerHTML = "Good job! You guessed the number!";

} else {

document.getElementById("randNum").innerHTML = "Wrong! The answer was " + number + "!";

}
}
}

EDIT: I changed how the random number generator works but I'm still getting an error. And to add more detail, the page says Invalid entry

Two issues:

The data type returned by prompt is string, so calculations might go wrong if you don't explicitly convert it to number. You can do this by applying the unitary + operator, like +prompt('....');

Secondly, the way to get random numbers between min and max should be different. Change this:

number = Math.floor((Math.random() * max) + min);

to:

number = Math.floor(Math.random() * (max - min + 1) + min);

The corrected code:

var max = +prompt("Max guessing number?");

if (max <= 2) {
document.getElementById("randNum").innerHTML = "Invalid entry";
} else {

var min = +prompt("Wat is het kleinste nummer dat je kan raden?");
if (min >= (max - 1) || min <= 0) {
document.getElementById("randNum").innerHTML = "Invalid entry";

} else {

number = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(min, max, number, (max - min + 1));

if (guess > max || guess < min) {

document.getElementById("randNum").innerHTML = "Invalid entry";

} else if (guess == number) {

document.getElementById("randNum").innerHTML = "Good job! You guessed the number!";

} else {

document.getElementById("randNum").innerHTML = "Wrong! The answer was " + number + "!";

}
}
}
<div id="randNum" ></div>