Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone help me with this problem?! Using some form of loop, create a MPG ca

ID: 3759918 • Letter: C

Question

Can someone help me with this problem?!

Using some form of loop, create a MPG calculator. Ask the user if they're taking a trip, then ask for miles and gallons. After you've gotten this information, compute the MPG for that trip. Repeat until the user indicates they're not taking a trip. Then compute the total MPG for the entire set of trips.

Here's an example run. The input is in bold.

Are you taking a trip? Enter 1 for yes or 0 for no
1
How many miles for this trip?
50
How many gallons for this trip?
2
The MPG for this trip was 25.0
Are you taking a trip? Enter 1 for yes or 0 for no
1
How many miles for this trip?
300
How many gallons for this trip?
8
The MPG for this trip was 37.5
Are you taking a trip? Enter 1 for yes or 0 for no
0
The total MPG was 35.0

Explanation / Answer

package current;

import java.util.Scanner;

public class MilesPerGallon {

   public static void main(String[] unused)throws InterruptedException {
       Scanner scan = new Scanner(System.in);
       float totalMpg = 0;
       int option = -1;
       float miles = 0;
       float gallons = 0;
       float mpg = 0;
       do {
           System.out.println("Are you taking a trip? Enter 1 for yes or 0 for no");
           option = scan.nextInt();
           if(option == 1) {
               System.out.println("How many miles for this trip?");
               miles = scan.nextFloat();
               System.out.println("How many gallons for this trip?");
               gallons = scan.nextFloat();
               mpg = miles/gallons;
               System.out.println("The MPG for this trip was: "+mpg);
               totalMpg += mpg;
           }
       } while(option != 0);
  
       System.out.println("The total MPG was: "+totalMpg);  
   }
}

--------------output--------------

Are you taking a trip? Enter 1 for yes or 0 for no
1
How many miles for this trip?
50
How many gallons for this trip?
2
The MPG for this trip was: 25.0
Are you taking a trip? Enter 1 for yes or 0 for no
1
How many miles for this trip?
100
How many gallons for this trip?
4
The MPG for this trip was: 25.0
Are you taking a trip? Enter 1 for yes or 0 for no
0
The total MPG was: 50.0

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote