Hey everyone. I am supposed to create a program that will input the miles driven and gallons used for each tank full of gas. program has to calculate and display the miler per gallon obtained for each tankful and print the combined miles per gallon for all tank fulls up to that point. I have the program mostly figured out, i only have one problem...the total mpg for all tanks is not calculating right. the int milesdriven and gallonsused are supposed to stand for the totals used for each. i think i might need to increment them somewhere/somehow but im not sure exactly what to do. can anyone help?

import java.util.Scanner;
public class mpgcalc {

	public static void main(String[] args) {

		int tankCounter=0;
		int gallons=0;
		int miles=0;
		int milesdriven=0;
		int gallonsused=0;
		
		System.out.println("Welcome to the mpg calculator.");
		System.out.println(" ");
		
		Scanner input= new Scanner(System.in);
		
		System.out.print("Enter Miles Driven, or -1 to quit: ");
		miles=input.nextInt();
		
		milesdriven= milesdriven + miles;
		gallonsused=gallonsused + gallons;
		
		while (miles !=-1)
		{
			System.out.print("Enter Gallons Used: ");
			gallons=input.nextInt();
			
			milesdriven++;
			gallonsused++;
			tankCounter = tankCounter+1;
			
			System.out.println("MPG for tank " + tankCounter + " is " + miles/gallons);
			System.out.println("Total MPG for all tanks is " + milesdriven/gallonsused);
			System.out.println(" ");
			System.out.print("Enter Miles driven, or -1 to quit: ");
			miles=input.nextInt();
			System.out.print("Enter Gallons Used: ");
			gallons=input.nextInt();
		}

		System.out.println("Thank you for using the mpg calculator, now exiting.");
		System.exit(0);
	}

}

figured it out on my own. thanks anyways!

Your statement on line 21 does nothing because 'gallons' is 0. Saying gallonsused++ adds one to gallonsused. Inside your while loop, what you want to be doing is saying gallonsused = gallonsused + gallons. (Or, equivalently, gallonsused+=gallons). You also only need to prompt the user for the gallons used once -- right after the start of the while loop. You have it in there twice.

You have a couple of other mistakes but they are along the same lines. Once you update those that I mentioned I'll come back and see if I can give you some more help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.