Reputation: 979
I want the user to input a number between 1-100, until the user inputs a valid number, the loop will keep saying "That input is invalid".
My code is below. Where did I go wrong?
// Initialize var userGuess
var userGuess;
// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
for (var valid = false; valid == true;) {
userGuess = prompt("Guess a number");
if ((userGuess >= 1) && (userGuess <= 100)) {
valid = true;
} else {
valid = false;
console.log("That number is invalid! Please enter a number between 1-100");
}
}
Upvotes: 1
Views: 1164
Reputation: 3946
// Initialize var userGuess
var userGuess;
// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
var valid = false;
while(!valid){
userGuess = prompt("Guess a number");
if ((userGuess >= 1) && (userGuess <= 100)) {
valid = true;
} else {
console.log("That number is invalid! Please enter a number between 1-100");
}
}
// Initialize var userGuess
var userGuess;
With a for loop
// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
for(var valid = false; !valid){
userGuess = prompt("Guess a number");
if ((userGuess >= 1) && (userGuess <= 100)) {
valid = true;
} else {
console.log("That number is invalid! Please enter a number between 1-100");
}
}
Upvotes: 5
Reputation: 6785
Personally, In your scenario of trying to capture a valid user input, I would be more inclined to use a recursive function call.
function userValue(){
var guess = prompt("Guess a number")
if(guess > 0 && guess <= 100){
return guess;
}
return userValue();
}
var value = userValue();
I have made a few applications with this method. Its your call.
W
Upvotes: 1