Miles per gallon (MPG) calculation. Given a file containing data about the miles
ID: 3872915 • Letter: M
Question
Miles per gallon (MPG) calculation. Given a file containing data about the miles driven and the gallons of gas used per trip, write a Java program that calculates the MPG per trip and overall MPG. Sample input file as below:
350 12.3
200 10.1
500 18.7
Each line contains the miles driven and gallons used for a single trip. The input file name must be given through the first command line argument args[0].
The output for the above input should look like below:
Trip 1: 28.5
Trip 2: 19.8
Trip 3: 26.7
Overall: 25.5
The output has to be written into a file. The output file name is given through the second command line arguments args[1].
Explanation / Answer
import java.io.*;
import java.util.*;
import java.lang.*;
public class DemoMPG{
public static void main(String[] args){
File file = new File(args[0]);
try {
int total_miles = 0;
double total_gallons = 0;
int count = 0;
FileWriter fw = new FileWriter(args[1]);
BufferedWriter bw = new BufferedWriter(fw);
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
count++;
int miles = sc.nextInt();
double gallons = sc.nextDouble();
System.out.println("Trip " + count + ":" + String.format("%.1f",miles/gallons) );
bw.write("Trip " + count + ":" + String.format("%.1f",miles/gallons)+" ");
total_miles = total_miles + miles;
total_gallons = total_gallons + gallons;
}
System.out.println("Overall: " + String.format("%.1f",total_miles/total_gallons));
bw.write("Overall: " + String.format("%.1f",total_miles/total_gallons) +" ");
bw.close();
sc.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}