IN JAVA LANGUAGE: Look at the file “rainfall.txt”. Copy this file in your hard d
ID: 3834392 • Letter: I
Question
IN JAVA LANGUAGE:
Look at the file “rainfall.txt”. Copy this file in your hard drive. This file contains several lines. Each line contains exactly 13 columns. The first column represents the year. The next 12 columns represent the rainfall (in inches) during the 12 months in that particular year in Houston. Assume that the user doesn’t know how many lines are there in the file, but each line has exactly 13 columns. Here, you need to write a java program that opens the file, read the info from the file, and calculates the following
a) The total rainfall in each year.
b) The average monthly rainfall in each year.
c) In each year, find the month (just display the month number) which received the highest amount of rainfall.
After the program calculates the above, the program should write the results in a new file called “Houston_rainfall.txt”.
Explanation / Answer
Here is the code for you:
import java.io.*;
import java.util.*;
class TotalAndAvgRainfallPerYear
{
public static double calculateTotal(double[] data)
{
double sum = 0.0;
for(int i = 0; i < data.length; i++)
sum += data[i];
return sum;
}
public static int monthWithHighestRainfall(double[] data)
{
int month = 0;
for(int i = 1; i < data.length; i++)
if(data[i] > data[month])
month = i;
return month+1;
}
public static void main(String[] args) throws FileNotFoundException
{
//Opens the file "rainfall.txt"
Scanner sc = new Scanner(new File("rainfall.txt"));
PrintWriter fw = (new PrintWriter(new File("Houston_rainfall.txt")));
while(sc.hasNextLine())
{
//Read the info from the file
//The first column represents the year
int year = sc.nextInt();
//The next 12 columns represent the rainfall (in inches) during the 12 months in that particular year in Houston.
double[] rainfall = new double[12];
for(int i = 0; i < 12; i++)
rainfall[i] = sc.nextDouble();
//Calculates the following:
//a) The total rainfall in each year.
double totalRainfall = calculateTotal(rainfall);
//b) The average monthly rainfall in each year.
double avgRainfall = totalRainfall / 12;
//c) In each year, find the month (just display the month number) which received the highest amount of rainfall.
int highestRainfallMonth = monthWithHighestRainfall(rainfall);
//Write the results in a new file called "Houston_rainfall.txt".
fw.write(year + " " + totalRainfall + " " + avgRainfall + " " + highestRainfallMonth + " ");
}
fw.close();
}
}