Program Logic

Unit 7 Index

Combining Structures

Combining Repetition and Decision Structures

Many times you will need to make a decision before entering a loop and/or make a decision from within a loop. Both could alter the course of the program. Combining programming techniques, such as loops and decision structures, is extremely common. In fact, you should make sure that combining the basic programming concepts is in your bag of tricks.

Testing for true

Does the way the conditions are coded below look odd to you? These represent implied condition testing.

//implied condition test for true
while(loopTest) {
  //do something
}

do{
  //some code
}while(loopTest);

The below code snippets represent explicit condition testing.

//Explicit condition test for true
while(loopTest == true) {
  //do something
}

do{
  //some code
}while(loopTest == true);

Testing for false

Remember, the exclamation point negates an expression. In other words, we are checking to see if the condition is false. Sometimes, checking for false allows for more streamlined code.

//implied condition test for false
while(!loopTest) {
  //do something
}

do{
  //some code
}while(!loopTest);

The below code snippets represent explicit condition testing.

//Explicit condition test for false
while(loopTest == false) {
  //do something
}

do{
  //some code
}while(loopTest == false);

Remember, in a while or do/while loop, the condition that is being tested is a Boolean expression. A Boolean expression always tests for true. For that reason, we do not have to explicitly test our variable value using the comparison operator (==). Think of it as shorthand: while(loopTest) is shorthand for while(loopTest == true). This shorthand expression is used quite often in textbooks and industry.

Code Example

Please study the below code. The method, loopWithIf(), asks for entries from the end-user and displays the entry in the console. The code will continue asking for entries until the end-user enters "Q". In the statement: while(loopAgain) the comparison to true is implied. while(loopAgain) is shorthand for: while(loopAgain == true). Notice the value of loopAgain is initialized to true. The value of loopAgain only changes within the decision structure.


private void loopWithIf() {
     String entry = "";
     boolean loopAgain = true;
     final String QUIT = "Q";
     Scanner input = new Scanner(System.in);

     do{
          System.out.println("Please enter something or 'Q' to stop.");
          entry = input.nextLine(); //.nextLine() allows spaces

          if (entry.equalsIgnoreCase(QUIT)) {
               loopAgain = false; //change the condition
               System.out.println("Good, bye!");
          }
          else {
               System.out.println("You entered: " + entry);
          }

     }while(loopAgain);//end of loop

}//end of method

Better Code Example

Please study the below code. Remember, the condition of a loop must be Boolean expression. So instead of introducing a Boolean variable, we can take advantage of the basic functionality of a loop. Notice in the code below, the while condition is now a Boolean expression while(!entry.equalsIgnoreCase(QUIT)). Here, we are saying "as long as the value of entry is NOT the same as QUIT keep looping". The while(!entry.equalsIgnoreCase(QUIT)) is shorthand for: while(entry.equalsIgnoreCase(QUIT)== false). This version of the code is more sophisticated and shows a better understanding of the internal workings of a loop. Notice that the condition is in the negative (is NOT), whereas the nested decision statement is in the positive.


private void loopWithIf() {
     String entry = "";
     final String QUIT = "Q";
     Scanner input = new Scanner(System.in);

     do{
          System.out.println("Please enter something or 'Q' to stop.");
          entry = input.nextLine(); //.nextLine() allows spaces

          if (entry.equalsIgnoreCase(QUIT)) {
               System.out.println("Good, bye!");
          }
          else {
               System.out.println("You entered: " + entry);
			   System.out.println();  //blank line
          }

     }while(!entry.equalsIgnoreCase(QUIT));//end of loop

}//end of method

Repetition Structure with Nested Decision

The loopWithIf() example illustrates a great opportunity for using the do/while loop. Remember, the do/while loop is guaranteed to run at least once. Nesting a decision structure inside of a repetition structure gives the developer a lot of control and is very handy if you need to send your code to another method. Typically, this method would return a Boolean value back to your decision structure.

I also combined loops and decision structures in the guessMyNumber() example on the condition-controlled loops web page. Please revisit that example and notice that the decision structure has the loop nested inside of it. With the method guessMyNumber(), we never enter the loop if the end-user did not enter a number.

Do you think it is possible to write code so the end-user is entering numbers, but they still enter a "Q" to quit? It is. Here is a hint. Get the end-user input into a String variable. If their input is the same as your quit variable, you know to quit. But, if the end-user entered a valid number you would convert the “string number” into a “numeric number” using the library function: Integer.parseInt(). Remember to validate the entry first to insure it can be parsed. You can use a regular expression to validate if the input can be parsed into a number.

Things to Remember

In many programming languages, when you declare a boolean variable it is automatically initialized (under the covers) to either true or false. The initial value given to a boolean variable depends on the language you are using.

In Java, if you use the primitive type boolean the variable is initialized to false, however, if you use the wrapper class, Boolean then the default value is null. The bottom line is, when in doubt, explicitly initialize the variable. That way, you know what its value is, plus you maintain control. I know I do not always initialize, but generally speaking, relying on default values is considered a bad programming habit.

The value for your Boolean expression can come as a returned Boolean value from a method. Remember isValidNumber()? That method returned a Boolean, so you could constructor your loop condition similar to this: while(!isValidNumber(dataToValidate)). When combining loops and decisions, the loop can be on the outside or the inside of a decision structure.

Input Validation

You have probably heard me say never, ever, ever trust what the end-user enters. If an end-user can enter the wrong thing then they will enter the wrong thing and the reality is, if an end-user enters the wrong thing, your program may fail. It is up to you to code your programs defensively to avoid crashes.

There is an old adage, “Garbage In, Garbage Out” (GIGO). Using the while or do/while loop is a good way of keeping garbage out of your system. Your code may read like this: While the end-user is keying in a value that is out of range, keep asking for a new value.

Detailed Example

The example code combining repetition and decision structures shows you how to check for even numbers. In this example, I nest a repetition structure inside of a decision structure, as well as, a decision structure inside of the repetition structure. I also use a regular expression and the modulo operator.

What's Next

After carefully reviewing the sample code on this page and linked above, go to the chapter on Nested Loops.