Program Logic

Unit 7 Index

Condition-Controlled Loops

Condition-Controlled Loops

We do not always know the exact number of times to iterate through a loop. This is a common situation when the end-user is in charge of letting the program know when they are done with data entry. As a developer, your job is to write the program that will loop until a predetermined value, such as “quit”, is read. The predetermined value is known as a sentinel.

Stop on a Sentinel

sen•ti•nel

Definition: (noun)...a soldier or guard whose job is to stand and keep watch.

The term sentinel in programming means a special value that a program is looking for and when encountered, take certain actions. Here are some examples.

Below is a Java code snippet that uses the while loop with a sentinel. I encourage you to type the code into your development environment AND make it work. Remember to read my comments as they help you understand the concepts.


private void getCities() {

  //IMPORTANT you need to have a condition to check
  //make sure you get the condition OUTSIDE of the while loop
  //make sure you give the opportunity to change the condition INSIDE 
  //of the while loop
  
  Scanner input = new Scanner(System.in);
  String city = "N";
  final String QUIT = "Q";

  System.out.println("Please enter a city that you have lived in.");
  System.out.println("When you want to quit, just enter 'Q' for quit");
  System.out.println();

  //IMPORTANT, you must get the "condition" OUTSIDE of the loop first
  //the "condition" is stored in the variable city
  //I use nextLine to capture cities with spaces in them

  city = input.nextLine();

  //IMPORTANT notice the ! The ! (not operator) means negate the statement.
  //the signature of this while loop says:
  //as long as the city is NOT equal to the value of the 
  //named constant QUIT, keep going
  
  while(!city.equalsIgnoreCase(QUIT)){
    //order matters
    System.out.println("I like " + city);
    System.out.println("Please enter another city or 'Q' to quit");

    //IMPORTANT, use the built in Scanner method .nextLine() 
    //just in case the city has a space in its name

      city = input.nextLine();

  } //end while

  System.out.println("Thank you!");

}//end of method

Below is a sample output for the code above. Please read through the output to insure it is what you expected.


	Hello, I would like to know the cities you have lived in
	When prompted, please enter a city or 'Q' to quit
	
	Please enter a city that you have lived in.
	When you want to quit, just enter 'Q' for quit

	River Falls
	I like River Falls 
	
	Please enter another city or 'Q' to quit
	Las Vegas
	I like Las Vegas

	Please enter another city or 'Q' to quit
	q
	
	Thank you!

Using Two Sentinels

Sometimes you need two sentinels; one to solve the problem and one to allow the end-user to just quit.With a method such as guessMyNumber(), the end-user may get tired of playing before they actually guess the number. By providing a “quit” sentinel, you allow the end-user to gracefully end the program. However, you also need to watch for the magic number to award fabulous prizes.

Below is a Java code snippet that uses the while loop with two sentinels. Study the code and my comments carefully. Ask questions if you do not fully understand this fundamental concept. I encourage you to type the code into your development environment AND make it work.

Notice that I use a decision structure to validate the end-user input. Remember, never trust end-user input. Always validate. Please study the code below.


private void guessMyNumber() {

//IMPORTANT you need to have a condition to check
//make sure you get the condition OUTSIDE of the while loop
//make sure you give the opportunity to change the condition INSIDE 
//the while loop

  Scanner input = new Scanner(System.in);
  int guess = 0;
  String userInput = "";
  final int QUIT = 99;
  final int FAV_NUM = 57;

  System.out.println("Please enter a number.");
  System.out.println("If you get tired of guessing and you want" +
		" to quit, just enter 99");
		
  System.out.println();
	
//Remember end-user validation? 
//I use .next() and save the end-user's input into a String variable. 
//Because this is safe...your program will not crash. A String can
//hold a series of any characters, including numbers.

  userInput = input.next();

//Use a regular expression "[0-9]+" to see if the end-user input matches
//the numbers 0-9. The + signs means the number can occur more than once.
      
  if(userInput.matches("[0-9]+")){
	
  //IMPORTANT, you must get the "condition" OUTSIDE of the loop first
  //the "condition" needs to be stored in the variable guess, but we saved
  //it into a String variable named userInput. Not to worry...parse it!
  //It is safe to parse userInput because we validated it to be a number
  //using the regular expression in our decision structure
  
   guess = Integer.parseInt(userInput);

//IMPORTANT notice the ! The ! (not operator) means negate the statement.
//the signature of this while loop says:
//as long as the guess is NOT equal to FAV_NUM AND it is NOT equal to 
//the value of QUIT, keep going

    while(guess != FAV_NUM && guess != QUIT ){
      //order matters
      System.out.println("Sorry, that is not correct");
      System.out.println("Please try again or enter 99 to quit");

      //NEVER trust end-user input. VALIDATE again

      userInput = input.next();

      if(userInput.matches("[0-9]+")){
        guess = Integer.parseInt(userInput);
      }
      else{
        break; //get out of the loop
      }
		
    }//end of while
   
  }//end of if(userInput.matches)
  
  if(guess == FAV_NUM){
	System.out.println("Wow, you guessed it.");
  }
  else{
	//under which conditions does this statement run?
	System.out.println("Bye! Come back soon.");
  }
  
}//end of method

Remember the logical AND ( && ) operator? In our while loop, both conditions MUST reconcile to true in order for the loop to run. The conditions read, “is it true that guess is not equal to the value of FAV_NUM and is it true that guess is not equal to the value of QUIT.” In this example, we use the same variable on both sides of the condition. Pay attention to the data types!

Things to Remember

What's Next

After carefully reviewing the code snippets on this page, go to the chapter on Combining Repetition Structures and Decision Structures. After all, the sample code on this page gave you a preview.