Home > Software design >  How to re-prompt a user after invalid input?
How to re-prompt a user after invalid input?

Time:02-16

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:

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

CodePudding user response:

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

CodePudding user response:

This should work

int[] year = new int[12];
int month = 0;
while (month < 12) {
   int rain = myScanner.nextInt();
   if ( rain >= 0) {
      year[month] = rain;
      month  ;
   } else {
      System.out.println("enter a positive value");
   }
}
  •  Tags:  
  • java
  • Related