Can someone explain to me what a sentinel does in Java? Or how it works?

Oyukyfairy picture Oyukyfairy · Feb 10, 2014 · Viewed 39.9k times · Source

I am trying to understand what sentinel is or how it works with the program. Anyways this is the block of code I am trying to understand. I know it is a sentinel control loop, but I don't know what it does.

private static final int SENTINEL = -999

From what I have Googled is that by having a negative integer it indicates the end of a sequence. But how does it do that? Oh, and how do I initialize the sentinel? Is it already initialized?

public static int gameScore(int[] teamBoxScore) { //This is telling me the name of an array
int output = 0;
for (int v : teamBoxScore){ //I know that this the values of the array will be stored in the variable "v".
     if (v !=SENTIENL) {// 
         output += v; 
      }
}
return output;
} 

Please and Thank you! I am learning how to code with Java

Answer

Tony the Pony picture Tony the Pony · Feb 10, 2014

There is nothing special about a "sentinel." It is simply any constant of your choosing that is not a legitimate value in a data set, so you can use it to mark the end of a sequence. For example, if a team's box score will never be less than zero, -999 (or any other negative value) can be used as a break/end marker.

Usually, there are better, cleaner ways to do this.