In: Computer Science
How’s the Weather
Purpose
To enhance your ability to properly index and retrieve items in an array in Java
Directions and examples:
The FAS 2720 class this semester was tasked with writing a research paper on temperature change and its effect on crops. A student comes to you for help, and asks if you can make him some software that will compute the average temperatures throughout a five-day period. Write a program that prompts the user for all of the temperatures over the five-day period (sunrise, noon and sunset for each day), then compute and display the average temperature on each day of the week, and the average temperature at sunrise, noon, and sunset across all five days.
Output:
Day 1:
Enter Sunrise Temperature: 65
Enter Noon Temperature: 75
Enter Sunset Temperature: 63
Day 2:
Enter Sunrise Temperature: 68
Enter Noon Temperature: 85
Enter Sunset Temperature: 70
Day 3:
Enter Sunrise Temperature: 60
Enter Noon Temperature: 70
Enter Sunset Temperature: 65
Day 4:
Enter Sunrise Temperature: 69
Enter Noon Temperature: 90
Enter Sunset Temperature: 73
Day 5:
Enter Sunrise Temperature: 70
Enter Noon Temperature: 89
Enter Sunset Temperature: 76
Day 1 Average = 67.66666666666667
Day 2 Average = 74.33333333333333
Day 3 Average = 65.0
Day 4 Average = 77.33333333333333
Day 5 Average = 78.33333333333333
Sunrise Average = 66.4
Noon Average = 81.8
Sunset Average = 69.4
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//2D matrix where row represents days and columns represents 3 periods
int[][] temp = new int[5][3];
//user input for 5 day and 3 periods for each and stores it in 2D matrix
for(int i = 0; i < 5; i++)
{
System.out.println("Day " + (i+1) + ":");
for(int j = 0; j < 3; j++)
{
if(j==0)
System.out.print("Enter Sunrise Temperature: ");
if(j==1)
System.out.print("Enter Noon Temperature: ");
if(j==2)
System.out.print("Enter Sunset Temperature: ");
temp[i][j] = sc.nextInt();
}
}
//calculates average of 5 days
for (int i = 0; i < 5; i++)
{
double rowSum = 0;
//calculates sum of row means days
for (int j = 0; j < 3; j++)
{
rowSum += temp[i][j];
}
System.out.println("Day " + (i+1) + " Average " + rowSum / 3);
}
//calculates average of 3 periods
for (int i = 0; i < 3; i++)
{
double columnSum = 0;
//calculates sum of column means periods
for (int j = 0; j < 5; j++)
{
columnSum += temp[j][i];
}
if(i==0)
System.out.println("Sunrise Average: " + columnSum / 5);
if(i==1)
System.out.println("Noon Average: " + columnSum / 5);
if(i==2)
System.out.println("Sunset Average: " + columnSum / 5);
}
}
}
Please refer below screenshot of code for your better understanding of indentation of code.
Sample Output :