This program gets the number of miles traveled and the gallons of gas used, and
ID: 3733955 • Letter: T
Question
This program gets the number of miles traveled and the gallons of gas used, and prints out MPG. You are to complete the method AND add a loop to main so that you continually ask for input and calculate MPG until the user gives you a zero for the miles traveled. NOTE: Do not ask for gallons of gas or call the method if miles is zero. I suggest you FIRST write the method and then worry about the loop.
import java.util.Scanner;
public class Number1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//get the miles traveled
System.out.println("Enter the number of miles traveled, 0 to stop");
double miles=keyboard.nextDouble();
System.out.println("Enter the amount of gas consumed");
//get the gas used
double gas=keyboard.nextDouble();
//output MPG
double mpg=MilesPerGallon(miles, gas);
System.out.println("Gas usage was " + mpg + " MPG");
}
public static double MilesPerGallon(double m, double g)
{ //calculates mpg by dividing miles by gallons
//and returns the result
}
}
Explanation / Answer
Number1.java
import java.util.Scanner;
public class Number1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//get the miles traveled
System.out.println("Enter the number of miles traveled, 0 to stop");
double miles=keyboard.nextDouble();
while(miles!=0)
{
System.out.println("Enter the amount of gas consumed");
//get the gas used
double gas=keyboard.nextDouble();
//output MPG
double mpg=MilesPerGallon(miles, gas);
System.out.println("Gas usage was " + mpg + " MPG");
System.out.println(" Enter the number of miles traveled, 0 to stop");
miles=keyboard.nextDouble();
}
}
public static double MilesPerGallon(double m, double g)
{ //calculates mpg by dividing miles by gallons
//and returns the result
return m/g;
}
}
_________________
Output:
Enter the number of miles traveled, 0 to stop
500
Enter the amount of gas consumed
5
Gas usage was 100.0 MPG
Enter the number of miles traveled, 0 to stop
450
Enter the amount of gas consumed
6
Gas usage was 75.0 MPG
Enter the number of miles traveled, 0 to stop
0
_____________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.