import java.io.*;
import java.util.*;
/* Application that reads temperatures from a file and stores them in
an array of integers. It then finds the average temperature and the
highest temperature. */
public class Weather
{
public static void main (String [] args)
{
CitiesWeather
city = new CitiesWeather ();
city.readTemperatures
();
city.displayStatistics
();
} // main method
} // class Weather
/* class that reads in temperatures, stores them in an array and displays
statistics. */
class CitiesWeather
{
final int maxSize = 20;
private int [] highs = new int [maxSize];
private int numberTemps = 0;
// Method that reads from a file and stores
the integers in an array.
public void readTemperatures ()
{
try
{
BufferedReader infile = new BufferedReader (new InputStreamReader (new
FileInputStream ("weather.txt")));
int temperature = Integer.parseInt (infile.readLine ());
while ((temperature > -20) && (numberTemps < maxSize))
{
highs [numberTemps] = temperature;
System.out.print (temperature + " "); // Echo data in file on the screen.
numberTemps ++;
temperature = Integer.parseInt (infile.readLine ());
}
System.out.println ();
} // try block
catch (IOException
ie) { System.out.println ("File not found.");}
catch (NumberFormatException
ex) { System.out.println ("Number format error.");}
} // method readTemperatures
// Find the average of all the integers in
the array.
private int calculateAverage ()
{
int sum = 0;
for (int count
= 0; count < numberTemps; count ++)
sum = sum + highs [count];
int average
= sum / numberTemps;
return average;
} // method calculateAverage
// Find the highest integer in the array.
private int findHighest ()
{
int highest,
location;
highest = highs
[0];
for (int count
= 1; count < numberTemps; count ++)
if (highest < highs [count]) highest = highs [count];
return highest;
} // method findHighest
// Get the average value and the highest value
and display them on the screen.
public void displayStatistics ()
{
int average
= calculateAverage ();
int highest
= findHighest ();
System.out.println
("The average high was " + average);
System.out.println
("The highest temperature was " + highest);
} // method displayAverage
} // class CitiesWeather
Contents of file, weather.txt
71
62
59
45
66
49
58
42
52
44
63
52
73
59
-20