Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to re-prompt a user after invalid input?

I have a program that asks the user for 12 months worth of rainfall data. The data being entered can not be below Zero.

How do I re-ask the user to enter valid data while the program stays on the same month?

Affected sections of code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for(int i = 0; i< month; i++){
            System.out.println("Please enter the rainfall for month " +
                    (i + 1) + ": ");
            thisYear[i] = myScanner.nextDouble();
        }

>Solution :

You could do this with a while loop
For example, let’s say we only want to except values between 1 and 12 we could do

for(int i = 0; i< month; i++){
  System.out.println("Please enter the rainfall for month " +(i + 1) + ": ");
  thisYear[i] = myScanner.nextDouble();
  while((thisYear[i] > 12) || (thisYear[i] < 1)) {//error message
    System.out.println("ERROR Please enter a valid entry");
    System.out.println("");
    System.out.println("Please enter the rainfall for month " +(i + 1) + ": ");
    thisYear[i] = myScanner.nextDouble();
  }
}

This would re prompt the user for an entry if it was outside of that range, you can also add additional parameters using || as logical or

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading