My program works perfectly except for one thing. Lets say I enter 3 years in the input box. The months change 1, 2, 3… but how do I change the year from 1 to 2 to 3 after each 12 month period? Currently, it just stays 1.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class AverageRainfall {
public static void main(String[] args) {
int y = 1;
int num_of_years = 0;
int total_num_of_months = 0;
int NUM_OF_MONTHS = 12;
double rainfall = 0;
double total_rainfall = 0;
double average_rainfall_per_month = 0;
String input;
input = JOptionPane.showInputDialog("Enter the number of years: ");
num_of_years = Integer.parseInt(input);
while (num_of_years < 1){
input = JOptionPane.showInputDialog("Invalid. Enter 1 or greater: ");
num_of_years = Integer.parseInt(input);
}
for (int i = 0; i < num_of_years; i++){
for(int j = 0; j < NUM_OF_MONTHS; j++){
input = JOptionPane.showInputDialog("Enter the rainfall, in inches, for each month." + "\n"
+ "Year " + (y + 1/12) + " Month " + (j + 1) + ":");
rainfall = Double.parseDouble(input);
while (rainfall < 0){
input = JOptionPane.showInputDialog("Invalid. Enter 0 or greater: ");
rainfall = Double.parseDouble(input);
}
total_rainfall += rainfall;
total_num_of_months++;
}
}
average_rainfall_per_month = total_rainfall / total_num_of_months;
System.out.println("Total number of months: " + total_num_of_months);
System.out.println("Total inches of rainfall: " + total_rainfall);
System.out.println("Average rainfall per month = " + average_rainfall_per_month);
}
}
>Solution :
...
total_num_of_months++;
}
//->increment year variable here
}