(java programming using while loops for the input validation and for loops for t
ID: 3623582 • Letter: #
Question
(java programming using while loops for the input validation and for loops for the
counter-controlled loops):
enter the number of years: 2
enter the data for year 1
Rainfall for month 1: 2.1
Rainfall for month 2: 3.3
Rainfall for month 3: 3.8
Rainfall for month 4: -5
Invaid entry. Please re-enter the rainfall for month 4: 3.9
Rainfall for month 5: 4.2
Rainfall for month 6: 4.5
Rainfall for month 7: 3.8
Rainfall for month 8: 2.9
Rainfall for month 9: 2.7
Rainfall for month 10: 2.1
Rainfall for month 11: 1.6
Rainfall for month 12: 1.8
Enter the data for year 2
Rainfall for month 1: 2.4
Rainfall for month 2: 2.9
Rainfall for month 3: 3.1
Rainfall for month 4: 3.4
Rainfall for month 5: 3.9
Rainfall for month 6: 3.7
Rainfall for month 7: -4
Invalid entry. Please re-enter the rainfall for month 7: 4.1
Rainfall for month 8: 3.5
Rainfall for month 9: 3.1
Rainfall for month 10: 2.8
Rainfall for month 11: 2.9
Rainfall for month 12: 1.7
Total number of months for which data was collected: 24
Total rainfall: 74.20 inches
Average monthly fainfall: 3.09 inches.
Explanation / Answer
import java.text.DecimalFormat;
import java.util.Scanner;
public class rainfallcalc {
public static void main(String[] args)
{
Scanner readUserInput = new Scanner(System.in);
float totalRainfall = 0;
System.out.print("Enter the number of years: ");
int years = readUserInput.nextInt();
for(int i=1; i < years+1; i++) {
System.out.println("Enter the number for year " + i);
for (int j=1; j < 13; j++) {
System.out.print("Rainfall for month " + j + ": ");
float data = readUserInput.nextFloat();
while (data < 0) {
System.out.print("Invalid entry. Please re-enter the railfall for month "+j + ": ");
data = readUserInput.nextFloat();
}
totalRainfall += data;
}
}
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("Total number of months for which data was collected:" + years*12);
System.out.println("Total rainfall: " + df.format(totalRainfall) + " inches");
System.out.println("Average monthly rainfall: " + df.format(totalRainfall/(years*12)) + " inches");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.