Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. First the program should ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate 12 times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.
Input Validation; Do not accept a number less than 1 for the number of years. Do not accept negative numbers for the monthly rainfall.Code:
package programmingChallenge;
import java.util.*;
public class AverageRainfall {
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int years,months = 12,totalmonths;
double month_inches,total_inches=0;
int a,b,c=1,d,e;
System.out.print("Enter Number of years: ");
years = sc.nextInt();
while(years<1 )
{
System.out.print("Enter a valid number of years: ");
years = sc.nextInt();
}
for(a=1;a<=years;a++)
{
for(b=1;b<=months;b++)
{
System.out.print("Enter the inches of rainfall for month no."+c+" : ");
month_inches = sc.nextDouble();
while(month_inches<0 )
{
System.out.print("Enter valid inches of Rainfall: ");
month_inches = sc.nextDouble();
}
total_inches += month_inches;
c++;
}
}
totalmonths = months*years;
System.out.println("Total Number of Months: \t"+totalmonths);
System.out.println("Total Inches of Rainfall:\t"+total_inches);
System.out.println("Average Rainfall per month:\t"+total_inches/totalmonths);
}
}
No comments:
Post a Comment