(TCOs 1–6) A trucking company has an application to track data from their trucks
ID: 2246491 • Letter: #
Question
(TCOs 1–6) A trucking company has an application to track data from their trucks regarding miles driven and fuel used each month. This information is stored in a file named “trucks.txt” . This table has the following fields. TruckID Truck Number (String) Miles Miles Driven (double) Fuel Fuel Used (double) Format of file – note the # delimiter character between fields TruckID#miles#fuel The application has a button that is clicked to read each line of the file and calculates and displays in the console the total miles driven, total fuel used, and average miles per gallon. You DO NOT have to write a separate class to process the data. The output in the console should look like: Total miles driven by all trucks xxx Total gallons of fuel used yyy Average miles per gallon for the fleet zz.zz The class method readFile() is called by the action listener to do the work. Write the code for this method.
Explanation / Answer
For testing purpose the function readFile() has been put in the class.
import java.io.*;
public class DemoRead {
public static void readFile(){
String line;
try {
InputStream fis = new FileInputStream("trucks.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
int total_miles = 0;
double avg = 0;
int total_gallons = 0;
while ((line = br.readLine()) != null) {
String[] words = line.split("#");
total_miles = total_miles + Integer.parseInt(words[1]);
total_gallons = total_gallons + Integer.parseInt(words[2]);
}
System.out.println("Total miles driven by all trucks " + total_miles);
System.out.println("Total gallons of fuel used " + total_gallons);
avg = total_miles/total_gallons;
System.out.println("Average miles per gallon for the fleet " + String.format("%.2f",avg));
} catch (Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
readFile();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.