Write a program that uses a two-dimensional array to store the highest and lowes
ID: 3644552 • Letter: W
Question
Write a program that uses a two-dimensional array to store the highest andlowest temperatures for each month of the year. The program should
output the average high, average low, and the highest and lowest temperatures
for the year. Your program must consist of the following functions:
a. Function getData: This function reads and stores data in the twodimensional
array.
b. Function averageHigh: This function calculates and returns the
average high temperature for the year.
c. Function averageLow: This function calculates and returns the average
low temperature for the year.
d. Function indexHighTemp: This function returns the index of the
highest high temperature in the array.
e. Function indexLowTemp: This function returns the index of the
lowest low temperature in the array.
(These functions must all have the appropriate parameters.)
Explanation / Answer
import java.io.*;
public class TemperatureAnalysis {
public static void main(String[] args) {
temper temp=new temper();
System.out.println("Storing high and low temperatures of each month:");
temp.getData();
System.out.println("Average high temperature for the year:"+temp.averageHigh());
System.out.println("Average Low temperature for the year:"+temp.averageLow());
System.out.println("Index of the highest high temperature in the array:"+temp.indexHighTemp());
System.out.println("Index of the Lowest low temperature in the array:"+temp.indexLowTemp());
}
}
class temper
{
double temperature[][]=new double[13][3];
public void getData()
{
for(int i=1;i<=12;i++)
{
try{
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter the Highest and lowest temperature of month:"+i);
temperature[i][1]=Double.parseDouble(inp.readLine());
temperature[i][2]=Double.parseDouble(inp.readLine());
}
catch(Exception e){}
}
}
public double averageHigh()
{
double tot=0.0;
for(int i=1;i<=12;i++)
{
tot=tot+temperature[i][1]; // 1 st dimension has high value
}
return(tot/12.0);
}
public double averageLow()
{
double tot=0.0;
for(int i=1;i<=12;i++)
{
tot=tot+temperature[i][2]; // 2 nd dimension has low value
}
return(tot/12.0);
}
public int indexHighTemp(){
double max=temperature[1][1];
int index=1;
for (int i = 2; i <=12; i++)
{
if(temperature[i][1] > max)
{
max = temperature[i][1];
index=i;
}
}
return index;
}
public int indexLowTemp(){
double min=temperature[1][2];
int index=1;
for (int i = 2; i <=12; i++)
{
if(temperature[i][2] < min)
{
min = temperature[i][2];
index=i;
}
}
return index;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.