Home > Blockchain >  How to loop if invalid input in prompt
How to loop if invalid input in prompt

Time:12-03

For the final input, your program prompts the user for their year of study. Once again, this is not a required field, that is, a default value of 1 (as in 1st year of study) should be submitted if the user chooses to leave this field blank. Additionally, you must validate the data the user provides (if provided) to ensure that it is not less than 1, and not greater than 3 (valid range is 1-3 years of study).

If your solution detects invalid input, your program must loop to allow the user to re-enter year of study, this process continues indefinitely, until valid input is detected.


I have tried a few different methods and this is my most recent attempt, but after 5 hours, I needed to ask for help. Code is below ( Yes, I'm a noob :( )

do {
   var yearofStudy = prompt("Please enter your Year of Study", "1")
    console.log(yearofStudy)
    }
while
    ( yearofStudy > 1 && yearofStudy <4 )

CodePudding user response:

The condition is probably the inverse of what you mean. You probably want to keep prompting while the value is outside of the range 1-4.

do {
   var yearofStudy = parseInt(prompt("Please enter your Year of Study", "1"));
   console.log(yearofStudy)
} while ( yearofStudy < 1 || yearofStudy > 3 )

CodePudding user response:

As you didn't specified that you have to use do-while, then using while this way is totally okay and easier to understand.

You have some logical bugs, because your if statement, then (suppose that your code does work), you are checking if user input is bigger then 1, where if you input 1 it's equal to it -> but you're requested to accept that as a yearofStudy, also you need to check if user input is greater then 3, if yes, then ask for input again, you don't want to check if input is greater then 4 as you don't want accept grades 5,6,7,8,9....

var statement = true;
    while (statement){
    var yearofStudy = prompt("Please enter your Year of Study", "1");
    if(yearofStudy > 0 && yearofStudy < 4){
    break;
    }
 }
  • Related