In: Computer Science
Write a program that uses a two dimensional array to store the highest and lowest temperatures for each month of the calendar year. The temperatures will be entered at the keyboard. This program must output the average high, average low, and highest and lowest temperatures of the year. The results will be printed on the console. The program must include the following methods:
Directions
Source Code in Java:
import java.util.Scanner;
class TempStats
{
//creating array to store name of months
static String
months[]={"January","February","March","April","May","June","July","August","September","October","November","December"};;
static void inputTempForMonth(int temps[][],int month) //method to
input temperature for a given month
{
Scanner sc=new Scanner(System.in); //creating Scanner object for
inputs
System.out.println("Enter the high and low temperatures for the
month of "+months[month]+": ");
temps[month][0]=sc.nextInt(); //input
temps[month][1]=sc.nextInt(); //input
}
static int[][] inputTempForYear() //method to input temperature for
an year
{
int temps[][]=new int[12][2]; //creating 2D array to store
temperatures for an year
for(int i=0;i<12;i++)
inputTempForMonth(temps,i); //using method to input every
month
return temps; //returning the 2D array
}
static double calculateAverageHigh(int temps[][]) //method to
calculate and return average high temperature
{
double sum=0; //to store sum of all high temperatures
for(int i=0;i<12;i++)
sum+=temps[i][0]; //adding every high temperature to sum
return sum/12; //returning the average
}
static double calculateAverageLow(int temps[][]) //method to
calculate and return average low temperature
{
double sum=0; //to store sum of all low temperatures
for(int i=0;i<12;i++)
sum+=temps[i][1]; //adding every low temperature to sum
return sum/12; //returning the average
}
static int findHighestTemp(int temps[][]) //method to find highest
temperature for the year
{
int max=0; //taking first month as highest initially
for(int i=1;i<12;i++)
{
if(temps[i][0]>temps[max][0]) //comparing every month to current
max month
max=i;
}
return max; //returning index of max month
}
static int findLowestTemp(int temps[][]) //method to find lowest
temperature for the year
{
int min=0; //taking first month as lowest initially
for(int i=1;i<12;i++)
{
if(temps[i][1]<temps[min][1]) //comparing every month to current
min month
min=i;
}
return min; //returning index of min month
}
public static void main(String args[])
{
//calling other methods and printing output
int temps[][]=inputTempForYear();
System.out.println("Average high temperature:
"+calculateAverageHigh(temps));
System.out.println("Average low temperature:
"+calculateAverageLow(temps));
int max=findHighestTemp(temps),min=findLowestTemp(temps);
System.out.println("Highest temperature is "+temps[max][0]+" from
the month of "+months[max]);
System.out.println("Lowest temperature is "+temps[min][1]+" from
the month of "+months[min]);
}
}
Output: