Search code examples
javaloopssentinel

Java: How to close loop with sentinel after first input (when using multiple inputs)


I have spent hours trying to figure this out, so I apologize if it's an easy fix.

I would like to make this program more user-friendly. Everything works currently, but the sentinel requires I enter "0" for both miles drive and gas used. I would like the sentinel to end the program after I enter the "0" for miles only. Is this possible?

import java.util.Scanner;

public class Mileage

{

public static void main(String[] args)
{   //initialization
    Scanner sc = new Scanner(System.in);
    int miles = -1, gallons = -1,
            totalMiles = 0, totalGallons = 0;
    double average, runningAverage;
    //while loop with sentinel controlled repetition
    while (miles != 0 && gallons != 0)
    {   //get miles 
        System.out.println("Enter the amount of miles driven. (0 to exit)");
        miles = sc.nextInt();
        //get gallons
        System.out.println("Enter the amount of gallons used. (0 to exit)");
        gallons = sc.nextInt();
        //calc average
        average = (double) miles / gallons;

        //calc running average
        totalMiles += miles;
        totalGallons += gallons;
        runningAverage = (double) totalMiles / totalGallons;

        //output average only if values were entered, by using if statement
        if (miles != 0 && gallons != 0)
        {
            System.out.printf("Miles per gallon for this trip is %.1f%n", average);

            System.out.printf("Running average miles per gallon is %.1f%n", runningAverage);
        }
    }

}

}


Solution

  • When you do:

    miles = sc.nextInt();
    

    you can make a check for exit the program like:

    if(miles==0){
        System.exit(0);
    }
    

    just before:

    System.out.println("Enter the amount of gallons used. (0 to exit)");