Do the following exercise, using jGrasp: Write a program that prompts the user t
ID: 3585833 • Letter: D
Question
Do the following exercise, using jGrasp:
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.
Here is a sample run (the first three numbers are entered by the user, your program calculates the cost of driving):
You do not need to validate input (you may assume the user always enters positive numbers).
Don't forget to add comments to your code and use proper programming style.
3. Name your class A2 (that is an uppercase A followed by the number 2).
4. Save your Java file as: A2.java
Explanation / Answer
A2.java
import java.text.DecimalFormat;
import java.util.Scanner;
public class A2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the driving distance: ");
double distance = scan.nextDouble();
System.out.println("Enter the miles per gallon: ");
double miles = scan.nextDouble();
System.out.println("Enter price per gallon: ");
double price = scan.nextDouble();
double cost = (distance * price)/miles;
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("The cost of driving is $"+df.format(cost));
}
}
Output:
Enter the driving distance:
900.5
Enter the miles per gallon:
25.5
Enter price per gallon:
3.55
The cost of driving is $125.36
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.