let num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
while(isNaN(num_cap)) {
alert("Input must be a number, try again.");
num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
}
while(num_cap<=1) {
alert("Number must be greater than 1, try again.");
num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
}
I am new to programming, specifically javascript. I have written a higher-lower guess game and have resolved just about every issue I’ve come across in the code besides an issue where if my first while loop is triggered and again prompts the user for entry, If I then enter an input that should trigger the second while loop, it still passes through anyways. This problem doesn't happen if I simply begin with entering an input that triggers the second while loop without triggering the first. It only happens if I trigger the first while loop beforehand.
You need to check for both requirements (number is valid, and also larger than 1) at the same time.
let num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
while(isNaN(num_cap) || num_cap <= 1) {
alert("Input must be a number larger than 1, try again.");
num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
}
This is another example that I prefer because it does the parsing in once, in one place, also the validation check is simpler, just num_cap > 1:
let num_cap, isValid;
do {
num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
isValid = num_cap > 1;
if(isValid) { break; }
alert("Input must be a number larger than 1, try again.");
} while(!isValid);