简体   繁体   中英

Sentinel value does not exit while loop

// In the following program, initally when the user is greeted with the instructions he can simply enter the sentinel to exit the while loop, however, when you get the result of tickets you wish to buy, pressing 999 does not exit the program

import java.io.*;

public class ManyTickets
{

  public static void main (String [] args) throws IOException
  {
  String userInput;
  String userInput2;
  int intInput = 0;
  int intInput2 = 0;
  double total = 0.00;
  BufferedReader ageInput = new BufferedReader (new InputStreamReader (System.in));
  try{
    System.out.println("Please enter your age, or press '999' to exit.");
    userInput = ageInput.readLine();
    intInput = Integer.parseInt (userInput);
    while (intInput != 999)
    {
      if (intInput < 0 || intInput > 110)
        System.out.println("Invalid entry, or your age seems a bit too high to enter buy these tickets");
      else if (intInput <= 12)
      {
        total = total + 6;
        System.out.println("The ticket cost for 1 ticket is " + total);
      }
      else if (intInput <= 64)
      {
        total = total + 11;
        System.out.println("The ticket cost for 1 ticket is " + total);  
      }
      else
      {
        total = total + 8;
        System.out.println("The ticket cost for 1 ticket is $" + total);
      }
      System.out.println("So far, your tickets cost is: $" + total  );
      System.out.print("Would you like to buy more tickets? You can buy up to 1 more ticket per customer! If no press 999 to exit");
      userInput = ageInput.readLine();
      intInput2 = Integer.parseInt (userInput);  
      }
    }catch (NumberFormatException e){
       System.out.println("Please restart the program, and enter an integer instead!");
    }
  } 
  {
    double total = 0.0;
    System.out.println("Thank you,  The total cost for the ticket is: $" + total);
    System.out.println("Have a nice day!");
  }
}

You're using two different variables, intInput and intInput2 . I don't see why you need the second one (right before the catch block). Just reuse intInput , which is the one being checked against the sentinel value in your while loop.

You are not doing anything after the user enters 999. Break the loop when its 999 as below,

intInput2 = Integer.parseInt(userInput);

if (intInput2 == 999) {
 break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM