Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to increment years

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        ...
        total_num_of_months++;
    }
    //->increment year variable here
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading