In: Computer Science
Print greeting Prompt the user for starting odometer reading Use a while loop to validate that starting odometer reading is a positive number.
Initialize variables: last odometer reading, current odometer reading, leg number, total fuel, moreInput
While moreInput == ‘y’
Prompt the user for new odometer reading and fuel consumed If fuel is positive and new odometer reading > last odometer reading:
Calculate MPG for this leg using mpg = (new odometer – last odometer) / fuel Print MPG for this leg
Update last odometer reading, total fuel, leg number
Ask if user wants to continue (save user response in moreInput)
Else
Print message saying fuel should be positive and new odometer reading should be greater than last odometer reading
Print number of legs Calculate average MPG over entire journey (= Total miles travelled / total fuel consumed) Print average MPG over entire journey
Print Bye message.
hey there ! i am done with the code in java... Please give me a like to appreciate my work and efforts....
here is the code -
package MPG;
import java.util.Scanner;
/**
*
* @author Aditya kumar
*/
public class MPG {
public static void main(String args[])
{
//declaring variables
int lastodometer,currentodometer = 0,legnumber,totalfuel = 0;
char moreinput='y';
//for user input
Scanner sc=new Scanner(System.in);
//manually update the lastodometer
lastodometer=88;
legnumber=1;
double mpg;
//while loop
while(moreinput=='y')
{
//ask user to enter the values
System.out.println("Enter the newOdometer : ");
currentodometer=sc.nextInt();
System.out.println("Fuel consumed ? ");
totalfuel=sc.nextInt();
//check if totalfuel is positive and currentodometer is greater
than lastodometer
if(totalfuel>=0 &&
currentodometer>lastodometer)
{
//calculate mpg
mpg=(currentodometer-lastodometer)/totalfuel;
System.out.println("The MPG : "+mpg);
//set the values
totalfuel=totalfuel;
legnumber++;
lastodometer++;
//ask user to continue
System.out.println("Do you wanna continue ? y/n ");
moreinput=sc.next().charAt(0);
}
else
{
//else part
System.out.println("fuel should be positive and new odometer
reading should be greater than last odometer reading");
}
}
//calculate the average
double average=(currentodometer+lastodometer)/totalfuel;
System.out.println("average over entire journey : "+average);
System.out.println("Bye !");
}
}
and the snapshot of the output is -
Thank You ! Dont forget to like !