Thursday, June 19, 2014

Elementary Programming; Exercise No. 20

Write a program that prompts the user to enter the distance to drive, the fuel efficiency of the car in miles per gallon, and the price per gallon, and displays the cost of the trip.

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   double distance, milesPerGalon, pricePerGalon;
   double galonNeeded, cost;

   System.out.print("Enter the driving distance:");
   distance = s.nextDouble();

   System.out.print("Enter miles per gallon:");
   milesPerGalon = s.nextDouble();

   System.out.print("Enter price per gallon:");
   pricePerGalon = s.nextDouble();

   galonNeeded = distance / milesPerGalon;
   cost = galonNeeded * pricePerGalon;

   System.out.print("The cost of driving is $" + cost);
}

No comments:

Post a Comment

Author