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.
IN JAVA, PLEASE
CODE
import java.util.Scanner;
public class Main
{
//method drivingCost
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon)
{
//calculating cost to drive those miles
double cost = (dollarsPerGallon / milesPerGallon) * drivenMiles;
//returns cost
return cost;
}
//main method
public static void main(String args[])
{
//variables
double milesPerGallon, dollarsPerGallon;
//Scanner object for input data from console
Scanner sc = new Scanner(System.in);
//prompt for miles per gallon
System.out.print("Enter miles per gallon: ");
milesPerGallon = sc.nextDouble();
//prompt for dollars per gallon
System.out.print("Enter dollars per gallon: ");
dollarsPerGallon = sc.nextDouble();
//printing cost for 10 miles
System.out.printf("Cost for 10 miles: %.2f\n", drivingCost(10, milesPerGallon, dollarsPerGallon));
//printing cost for 50 miles
System.out.printf("Cost for 50 miles: %.2f\n", drivingCost(50, milesPerGallon, dollarsPerGallon));
//printing cost for 400 miles
System.out.printf("Cost for 400 miles: %.2f\n", drivingCost(400, milesPerGallon, dollarsPerGallon));
}
}
OUTPUT
CODE SCREEN SHOT
Get Answers For Free
Most questions answered within 1 hours.