In: Computer Science
We will make some changes to our first program. If you recall we began with, A car's gas mileage or miles-per-gallon (MPG) can be calculated with the following Formula: MPG = Miles Driven / Gallons of gas used. Write a class called Mileage. The Mileage class should have two private member variables called miles and gallons of type double. The class should have four public methods: setMiles and setGallons should use void return types; getMiles and getGallons should use double return types. It should have one more method called getMPG that performs the math calculation and returns the double MPG Write a program called MPGMain that asks the user for the number of miles driven and the gallons of gas used. It should call the Mileage class to calculate the car's MPG. The class should return the MPG to the MPGMain where it was called and display the value on the screen. (Format the display and limit the miles-per-gallon to 2 decimal places) in JAVA programming language
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
Mileage.java :
//java class
public class Mileage {
//member variables
private double miles;
private double gallons;
//public methods
//setter methods
public void setMiles(double m)
{
this.miles=m;//set miles
}
public void setGallons(double g)
{
this.gallons=g;//set gallons
}
//getter methods
public double getMiles()
{
return this.miles;//return
miles
}
public double getGallons()
{
return this.gallons;//return
gallons
}
//method to calculate MPG
public double getMPG()
{
return
getMiles()/getGallons();//return MPG
}
}
*******************************
MPGMain.java :
import java.util.*;//import package
//Java class
public class MPGMain {
//entry point , main method
public static void main(String[] args) {
//create object of scanner
class
Scanner sc=new
Scanner(System.in);
//creating object of Mileage
class
Mileage mileage=new
Mileage();
//asking number of miles
drive
System.out.print("Enter number of
miles drive : ");
mileage.setMiles(sc.nextDouble());//read and set mileage
//asking number gallons of gas
used
System.out.print("Enter number of
gallons of gas used : ");
mileage.setGallons(sc.nextDouble());//read and set gallons
//call method getMPG() and display
MPG
System.out.printf("miles-per-gallon
(MPG) : %.2f",mileage.getMPG());
}
}
======================================================
Output : Compile and Run MPGMain.java to get the screen as shown below
Screen 1 :MPGMain.java
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.