Drivers are concerned with the mileage that automobiles get. One driver has kept
ID: 3864133 • Letter: D
Question
Drivers are concerned with the mileage that automobiles get. One driver has kept track of several trips by recording the mile driven and gallons used for each tankful. Develop a Java application that will input the miles driven and gallons used (both as intergers) for each trip.
The program should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all the trips up to this point.
all averaging calculations should produce floating points results. use class Scanner and sentinel-controlled repetition to obtain the data from the user.
Explanation / Answer
HI, Please find my implementation.
Please let me know in case of any issue.
import java.util.Scanner;
public class AverageMilesGallons {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many trips ? ");
int n = sc.nextInt();
// creating array to store total miles driven and gallon used
int[] miles = new int[n];
int[] gallons = new int[n];
System.out.println(" Enter total miles and used gallons for each trip ");
for(int i=0; i<n; i++){
System.out.print("Enter total miles driven for trip "+(i+1)+" : ");
miles[i] = sc.nextInt();
System.out.print("Enter total gallons used for trip "+(i+1)+" : ");
gallons[i] = sc.nextInt();
}
System.out.println();
System.out.println("Miles Gallons Avearge");
float totalMiles = 0;
int totalGallons = 0;
for(int i=0; i<n; i++){
float avg = (float)miles[i]/(float)gallons[i];
totalGallons = gallons[i];
totalMiles = miles[i];
System.out.println(miles[i]+" "+gallons[i]+" "+String.format("%.3f", avg));
}
System.out.println();
System.out.println("Total mils per gallon: "+(String.format("%.3f", totalMiles/totalGallons)));
}
}
/*
Sample run:
How many trips ? 4
Enter total miles and used gallons for each trip
Enter total miles driven for trip 1 : 543
Enter total gallons used for trip 1 : 123
Enter total miles driven for trip 2 : 324
Enter total gallons used for trip 2 : 12
Enter total miles driven for trip 3 : 231
Enter total gallons used for trip 3 : 34
Enter total miles driven for trip 4 : 165
Enter total gallons used for trip 4 : 31
Miles Gallons Avearge
543 123 4.415
324 12 27.000
231 34 6.794
165 31 5.323
Total mils per gallon: 5.323
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.