Assignment:
Average Rainfall
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.
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package averagerainfall; import java.util.Scanner; /** * * @author uuuuuuu */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int years; int months; double rainfall = 0; double totalRainfall = 0.0; System.out.println("Enter the number of years:"); years = keyboard.nextInt(); for(int count = 1; count<= years;count++) { for(months = 1; months<=12;months++) { System.out.println("Enter inches of rainfall for month " + months); rainfall = keyboard.nextDouble(); totalRainfall += rainfall;; } System.out.println("Number of months: " + (months)); System.out.println("Total inches of rainfall: " + totalRainfall); System.out.println("Average rainfall per month: " + (totalRainfall/(years * months))); } } }
In the code, where do I put [rainfall>0]?
When I enter [1] for years, the output for number of months is [13], why isn't it [12], how do I fix it?
When I put [2] for years, why doesn't the number of months accumulate; it should be [24] months not [12] and [12] (in my case, it is [13] and [13] because of coding problems.'
I'll fix it the output decimal format into (##0.00) afterward.