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();
}
>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