Answer:
See explaination
Explanation:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SpendAnalysis {
// year 2014 data will be at index 0
// year 2015 data will be at index 1
// year 2016 data will be at index 2
// year 2017 data will be at index 3
// year 2018 data will be at index 4
private static int[] checkIssued={0,0,0,0,0}; // will store the count of check for the year
private static double[] totalAmount={0,0,0,0,0}; // will store the total amount spent for that year
private static final int BASE_YEAR=2014; // base year
// need to update the below line so that it points to the input text file need to be read
private static final String INPUT_FILE="D:\\spent.txt";
public static void main(String[] args) {
// first read all the data from the input file and populate the array
try {
populateData();
} catch (FileNotFoundException e) {
System.out.println(INPUT_FILE+" could not read. Program will terminate now.");
System.exit(1);
}
// second print the data in the console
reportSpending();
}
// read data from input file and update the two arrays
public static void populateData() throws FileNotFoundException {
Scanner fileInput = new Scanner(new File(INPUT_FILE));
while(fileInput.hasNext()){
String[] lineTokens = fileInput.nextLine().split("\\s+");
if(lineTokens.length==2){
int year = Integer.parseInt(lineTokens[0].trim());
double amount = Double.parseDouble(lineTokens[1].trim());
checkIssued[year-BASE_YEAR]+=1;
totalAmount[year-BASE_YEAR]+=amount;
}
}
}
// print the report in the console
public static void reportSpending(){
System.out.println(String.format("%-13s%-15s%-15s%-15s","Year","# Checks","Total Spent","Average Check"));
System.out.println(String.format("%-15d%-15d$%-15.2f$%-15.2f",2014,checkIssued[0],totalAmount[0],totalAmount[0]/checkIssued[0]));
System.out.println(String.format("%-15d%-15d$%-15.2f$%-15.2f",2015,checkIssued[1],totalAmount[1],totalAmount[1]/checkIssued[1]));
System.out.println(String.format("%-15d%-15d$%-15.2f$%-15.2f",2016,checkIssued[2],totalAmount[2],totalAmount[2]/checkIssued[2]));
System.out.println(String.format("%-15d%-15d$%-15.2f$%-15.2f",2017,checkIssued[3],totalAmount[3],totalAmount[3]/checkIssued[3]));
System.out.println(String.format("%-15d%-15d$%-15.2f$%-15.2f",2018,checkIssued[4],totalAmount[4],totalAmount[4]/checkIssued[4]));
int totalChecks = checkIssued[0]+checkIssued[1]+checkIssued[2]+checkIssued[3]+checkIssued[4];
double totalSpent = totalAmount[0]+totalAmount[1]+totalAmount[2]+totalAmount[3]+totalAmount[4];
System.out.println(String.format("%-15s%-15d$%-15.2f$%-15.2f","Overall Total",totalChecks,totalSpent,totalSpent/totalChecks));
}
}