问题
I need to validate the user output for three different prompts and thought this would work but it is not.
The first prompt need to validate any of the 8 states and territories of Australia.
The second prompt needs to validate that the user has entered a whole number.
The third prompt needs to validate that the user has entered a negative or positive number that can be whole or has decimals.
Then the whole thing needs to loop over again so the three prompts can be asked again. So it can build a table.
function ask() {
var stInput = '';
var populationInput = '';
var changeInput = '';
var entering = confirm('Confirm to add state or territory');
if (!entering) {
return;
} else {
while (true) {
stInput = prompt('Enter state or territory');
function validateUserChoice(stInput) {
if (stInput !== "Queensland" && stInput !== "New South Wales" && stInput !== "Victoria" && stInput !== "Tasmania" && stInput !== "Northern Territory" && stInput !== "Western Australia" && stInput !== "South Australia" && stInput !== "Australian Capital Territory") {
} else {
return false;
}
}
populationInput = prompt('Enter population for ' + stInput + '');
while(!isValid(populationInput)) {
alert('Your input was invalid');
populationInput = parseInt(prompt('Enter population for ' + stInput + ''));
}
changeInput = prompt('Enter growth rate for ' + populationInput + '');
while(!isValid(changeInput)) {
alert('Your input was invalid');
changeInput = parseFloat(prompt('Enter growth rate for ' + populationInput + ''));
}
break;
}
alert("invalid state or territory");
}
回答1:
I cannot speak to your larger problem, but I will tell you, any time I use a while
loop, I always program in a fail safe. I usually call them a safetyValve
. It keeps the system from being caught in an infinite loop and crashing. It looks a little like:
var myCondition = true;
var safetyValve = 0;
var safetyMax = 10000;
while (myCondition && safetyValve < safetyMax) {
...
safetyValve++;
}
来源:https://stackoverflow.com/questions/55822359/validating-and-looping-javascript