2.13 LAB: Driving cost - methods
Write a method drivingCost() with input parameters drivenMiles, milesPerGallon, and dollarsPerGallon, that returns the dollar cost to drive those miles. All items are of type double. If the method is called with 50 20.0 3.1599, the method returns 7.89975.
Define that method in a program whose inputs are the car's miles/gallon and the gas dollars/gallon (both doubles). Output the gas cost for 10 miles, 50 miles, and 400 miles, by calling your drivingCost() method three times.
Output each floating-point value with two digits after the
decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);
The output ends with a newline.
Ex: If the input is:
20.0 3.1599
the output is:
1.58 7.90 63.20
Your program must define and call a method:
public static double drivingCost(double drivenMiles, double
milesPerGallon, double dollarsPerGallon)
Note: This is a lab from a previous chapter that now requires the use of a method.
--------------------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
public class LabProgram {
/* Define your method here */
public static void main(String[] args) {
/* Type your code here. */
}
}
import java.util.Scanner;
public class LabProgram {
/* Define your method here */
public static double drivingCost(double drivenMiles,double milesPerGallon, double dollarsPerGallon) // Method Declaration
{
return (dollarsPerGallon*drivenMiles)/milesPerGallon; // Computation of Cost which is product of cost and distance divided by mileage
}
public static void main(String[] args) {
/* Type your code here. */
Scanner sc=new Scanner(System.in); // Declare Scanner object
double mpg=sc.nextDouble(); //Accepting miles per Gallon
double dpg=sc.nextDouble(); // Accepting Dollars per Gallon
System.out.printf("%.2f ", drivingCost(10,mpg,dpg)); // Computation when the driven distance in 10 miles
System.out.printf("%.2f ", drivingCost(50,mpg,dpg)); // Computation when the driven distance in 50 miles
System.out.printf("%.2f ", drivingCost(400,mpg,dpg));// Computation when the driven distance in 400 miles
System.out.println(); // Display an empty line
}
}
Get Answers For Free
Most questions answered within 1 hours.