Hi All, I'm only up to chapter 4 in an intro to java book (Deitel), so I'm sure this isn't the most efficient code, but there's just one thing I'm trying to learn: to get the code to execute correctly, I had to set my sentinel variable tripMiles twice, once inside the while statement and once before it.
Once before the while statement and once inside it. This seems redundant but is the only way I got it to work by trial and error. Anyone who'd like to educate me, I'd appreciate it.
import java.util.Scanner;
public class MPGs //begin class, MPGs
{
public static void main(String[] args)//main method for starting application
{
//declare variables
int tripMiles = 0;
int tripGas = 0;
int milesTotal = 0;
int gasTotal = 0;
double tripMpg = 0;
double mpgTotal = 0;
//initialize variables (necessary?)
Scanner input = new Scanner ( System.in);
System.out.println("Enter miles traveled this trip (or -1 to end program):");
tripMiles = input.nextInt();
// sentinel control
while (tripMiles >= 0)
{
System.out.println("Enter gas used this trip:");
tripGas = input.nextInt();
milesTotal = tripMiles + milesTotal;
gasTotal = tripGas + gasTotal;
tripMpg = (double) tripMiles / (double) tripGas;
mpgTotal = (double) milesTotal / (double) gasTotal;
System.out.printf("Miles total is: %d. MPG for this trip is %.2f.\n", milesTotal, tripMpg);
System.out.printf("Average MPG across all trips is %.3f.\n\n", mpgTotal);
//a second request for Miles for this trip
System.out.print ("Enter miles traveled this trip (or -1 to end program):");
tripMiles = input.nextInt();
}
System.out.println("Goodbye!");
}
}