Java Tutorial #13 — More loops! Sentinel and break;


Topics Discussed: More loop practice, sentinel / dummy record loops, breaking out of loops

Source Code Available Here


Sentinel control loops
A sentinel loop is a loop that is controlled by a ‘false’ value. These will be much more useful when we get into more advanced types of data storage (especially arrays, lists, arraylists, etc.). The program will run until this value comes up. Let let’s assume for a moment that we have some values that we want to iterate through:


Values we want to iterate through: 1, 7, 17, 43, 123,12,19, 4, 190, 23, 26, 44, 92, 81, 77, 41,4, 0

Now, with all those values a counter controlled loop just wouldn’t cut it since our values will vary so widely. Assuming that we didn’t know the number of entries the user was entering we would have one last option on how to end the loop, by adding a value onto the end of the data

New dataset: 1, 7, 17, 43, 123, 12,19, 4, 190, 23, 26, 44, 92, 81, 77, 41, 4, 0, -999

Now we can fashion a loop (in pseudocode) to take advantage of this oddball value:

while(x != -999){
     //process next record
}


The break statement
The break statement is used as a way to break out of a loop, it’s syntax is really quite simple, but it’s implementation can be tricky at times. To call the break statement in a program simply add break; while you’re in a loop. This will break out of the inner-most loop, example:

while(condition){
     while(condition2){
          if (condition==true){
               break;// this break will break out of the inner while but will stay inside the outer while.
          }//endif
     }//end inner while
//end outer while

In the above example it’s obvious that the break statement can give us additional control in our loops, but it comes at the cost of complexity. There will be some times in the future where we will have much more complicated loops where breaking out of one will return us to another at a strange point. Be certain that you plan your loops / breaks with care as they are tempestuous at best.