Search code examples
javajava.util.scannersentinel

Java is requiring sentinel value from two separate inputs


I've just come across sentinel controlled iteration and I'm having some difficulties. I have to make a program that obtains the mileage and gallons used from the user, calculates the total mpg. I am trying to use -1 as a sentinel value to exit the loop when the user has finished, but when I go to enter the value, Java doesn't terminate the program. Instead it asks for another value from gallons. How do I get it to accept the sentinel value from the first input?

Example:

Enter miles or -1 to exit

-1

Enter gallons

-1

Terminate

import java.util.Scanner;

public class Activity3_17 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        // processing phase
        int miles = 1;
        int gallons = 1;
        int totalMiles = 0;
        int totalGallons = 0;
        float mpg = 0;


        System.out.println("Enter miles or -1 to exit");
        miles = input.nextInt();

        System.out.println("Enter gallons");
        gallons = input.nextInt();

        while (miles != -1) {
            System.out.println("Enter miles or -1 to exit");
            miles = input.nextInt();

            System.out.println("Enter gallons or -1 to exit");
            gallons = input.nextInt();

            totalMiles = totalMiles + miles;
            totalGallons = totalGallons + gallons;


        }
        if (miles == -1) {
            System.out.print("Terminate");
        }
        else{
            mpg = (float) totalMiles / totalGallons;
            System.out.println(mpg);
            }

    }
}

Solution

  • You need to check if the user entered -1 inside the while loop. If they did, exit the loop using break and then terminate the program.

    mpg is still printed within the loop, but only after the check is made. This ensures that the user gave valid input.

    I decided to make the loop condition true since the loop should break if miles or gallons is -1.

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
    
        int miles = 1;
        int gallons = 1;
        int totalMiles = 0;
        int totalGallons = 0;
        float mpg = 0;
    
        while (true) {
            System.out.println("Enter miles or -1 to exit");
            miles = input.nextInt();
            if (miles == -1) break;
    
            System.out.println("Enter gallons or -1 to exit");
            gallons = input.nextInt();
            if (gallons == -1) break;
    
            totalMiles = totalMiles + miles;
            totalGallons = totalGallons + gallons;
            mpg = (float) totalMiles / totalGallons;
    
            System.out.println(mpg);
        }
        input.close();
        System.out.print("Terminate");
    }