(This is Java programming language only) The solution for chapter 5, question #
ID: 3533673 • Letter: #
Question
(This is Java programming language only) The solution for chapter 5, question # 7 PC on this website is an incorrect solution, what I need help for is the correct question #7 which is:
7. Average Rainfall:
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 twelve 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 chould display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period. (We are using class' with this challenge)
Input validation: Do not acept less than 1 for the number of years. Do not accept negative numbers for the monthly rainfall.
Output:
Enter the number of years: -2
Invalid. Enter 1 or greater: 2
Enter the rainfall, in inches, for each month.
Year 1 month 1: -3
Invalid. Enter 0 or greater: 3
Year 1 month 2: 5
Year 1 month 3: 7
Year 1 month 4: 9
Year 1 month 5: 6
Year1 month 6: 0
Year 1 month 7: 0
Year 1 month 8: 0
Year 1 month 9: 3
Year 1 month 10: 6
Year 1 month 11: 10
Year 1 month 12 8
Year 2 month 1: 7
Year 2 month 2: 6
Year 2 month 3: 10
Year 2 month 4: 8
Year 2 month 5: 4
Year 2 month 6: 0
Year 2 month 7: 0
Year 2 month 8: 0
Year 2 month 9: 4
Year 2 month 10: 15
Year 2 month 11: 12
Year 2 month 12: 5
Number of months: 24
Total rainfall: 128.0 inches
Average monthly rainfall: 5.333333333333333 inches (there are 15 3's)
Explanation / Answer
import java.util.Scanner;
public class rainfall{
public static void main(String args[])
{
int year = 0 ;
int flag = 0;
int rain=-1;
int count = 1;
int sum=0;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of years");
while(year<1){
year= in.nextInt();
if(year<1)
System.out.print("Invalid. Enter 1 or greater");
}
System.out.println("Enter the rainfall, in inches, for each month.");
while(count>=year){
count++;
for(int i =1;i<=12;i++)
{
System.out.print("Year"+ count +" month"+i);
while(rain<=-1){
rain = in.nextInt();
if(rain<0)
System.out.print("Enter the rainfall, in inches, for each month.");
}
sum = sum+rain;
rain = -1;
}
}
System.out.println("Number of months:" + year *12);
System.out.println("total rain fall " + sum);
System.out.println("Average monthly rainfall:" + (sum/(year*12))+"inches");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.