147k views
0 votes
Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate four times, once for each quarter. Each iteration of the inner loop will ask the user for the inches of rainfall for that quarter.

1 Answer

4 votes

Answer & Explanation:

Written in java

import java.util.Scanner;

public class Main{

public static void main(String[] args) {

int totalRainfall = 0;

int rainfall;

Scanner keyboard = new Scanner(System.in);

int year;

do {

System.out.println("Enter number of year(s): value must be greater than 0");

year = keyboard.nextInt();

} while (year < 1);

// {

//

// System.out.println("Invalid input, please enter a number greater than zero ");

//

// year = keyboard.nextInt();

//

// }

for (int i = 0; i < year; i++) {

for (int quarter = 1; quarter <= 4; quarter++) {

int currentYear = 1 + i;

System.out.println("Enter the inches of rainfall for year " + currentYear + " quarter " + quarter);

rainfall = keyboard.nextInt();

if(rainfall > -1){

totalRainfall += rainfall;

}

while (rainfall < 0) {

System.out.println("Enter the inches of rainfall for year " + currentYear + " quarter " + quarter +": value must be greater or equal to 0 ");

rainfall = keyboard.nextInt();

}

}

}

System.out.println("Average quarterly rainfall is: " + (totalRainfall/(year*4)));

System.out.println("Average yearly rainfall is: " + (totalRainfall/(year)));

}

}

User Gsysko
by
8.5k points