Loop that prompts user until valid input [closed]

怎甘沉沦 提交于 2019-12-12 03:34:49

问题


Question: How to continuously prompt user when age is invalid (below 0 above 200, or not-a-number)?

var userAge = prompt("Please enter your age");
while (isNaN(userAge)){
    alert("That's not a number, please retry.");
    var userAge = prompt("Please re-enter your age.");
}

if (userAge == 0){
    alert("So you're a baby!");
}
while( userAge < 0  || userAge >= 200){
    alert("I think you may be lying about your age.");
    var userAge = prompt("Please re-enter your age, don't lie this time.");
    {continue}
}

if (userAge > 0 || userAge < 200){
    alert("That's a good age."); 
}

</script>

回答1:


You can return from while loop with break statement. For example:

var userAge = prompt("Please enter your age");
while (true) {
    if (isNaN(userAge)) {
        alert("That's not a number, please retry.");
    } else if (userAge < 0 || userAge >= 200) {
        alert("I think you may be lying about your age.");
    } else {
        break;
    }
    var userAge = prompt("Please re-enter your age.");
}
if (userAge == 0) {
    alert("So you're a baby!");
} else {
    alert("That's a good age.");
}


来源:https://stackoverflow.com/questions/35044961/loop-that-prompts-user-until-valid-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!