The assignment I am doing is almost complete but the while loop doesn't exit.

package lessons;
import java.util.Scanner;

public class Chp4417 {

    public void determineMileage()
    {
        Scanner input = new Scanner(System.in);
        int miles, gallons; //read in the inputs.
        int counter = 0; // counter
        int totalGallons = 0; //calculate total up to this point
        double totalAvg = 0;
        double average, milesPerGallon;

        System.out.println("Enter the gallons used(-1 to end): ");
        gallons = input.nextInt();
        System.out.print("Enter the miles used: ");
        miles = input.nextInt();

        average = (double) miles / gallons;
        System.out.print("The miles / gallon for this tank was " + average + "\n");

        while( gallons != -1)
        {
            totalGallons = totalGallons + gallons;
            counter = counter + 1;

            System.out.print("\nEnter the gallons used(-1 to end): ");
            gallons = input.nextInt();
            System.out.print("Enter the miles used: ");
            miles = input.nextInt();            
            average = (double) miles / gallons;
            System.out.print("The miles / gallon for this tank was " + average + "\n");
            totalAvg = totalAvg + average;
        }
        if (counter != 0)
        {
            milesPerGallon = (double) totalAvg / counter;
            System.out.print("The overall miles / gallon was " + milesPerGallon + "\n");
        }   
    }
}

package lessons;

public class Chp4417main {

    public static void main(String args[])
    {
        Chp4417 myChp4 = new Chp4417(); 

        myChp4.determineMileage();
    }
}

Edited 3 Years Ago by pyTony: fixed formatting

This article has been dead for over six months. Start a new discussion instead.