Can someone explain to me what sentinels do in Java? Or how does it work?

I'm trying to understand what a watch is or how it works with the program. In any case, this is a block of code that I am trying to understand. I know this is a sentinel control cycle, but I don’t know what he is doing.

private static final int SENTINEL = -999

From what I have Google, is that having a negative integer, it indicates the end of the sequence. But how is this done? 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 thanks! I am learning how to code Java

+3
source share
3 answers

"". , , . , , -999 ( ) break/end.

.

+6

sentinel-controlled repetition . simple,

import java.util.Scanner; // program uses class Scanner

public class ClassAverage
{
  public static void main(String[] args)
  {
     // create Scanner to obtain input from command window
     Scanner input = new Scanner(System.in);

     // initialization phase
     int total = 0; // initialize sum of grades
     int gradeCounter = 0; // initialize # of grades entered so far

     // processing phase
     // prompt for input and read grade from user    
     System.out.print("Enter grade or -1 to quit: ");
     int grade = input.nextInt();                    

     // loop until sentinel value read from user
     while (grade != -1)
     {
        total = total + grade; // add grade to total
        gradeCounter = gradeCounter + 1; // increment counter

        // prompt for input and read next grade from user
        System.out.print("Enter grade or -1 to quit: "); 
        grade = input.nextInt();                         
     }

     // termination phase
     // if user entered at least one grade...
     if (gradeCounter != 0)
     {
        // use number with decimal point to calculate average of grades
        double average = (double) total / gradeCounter;                

        // display total and average (with two digits of precision)
        System.out.printf("%nTotal of the %d grades entered is %d%n",
           gradeCounter, total);
        System.out.printf("Class average is %.2f%n", average);
     }
     else // no grades were entered, so output appropriate message
        System.out.println("No grades were entered");
  }
} // end class ClassAverage

Enter grade or -1 to quit: 97
Enter grade or -1 to quit: 88
Enter grade or -1 to quit: 72
Enter grade or -1 to quit: -1

Total of the 3 grades entered is 257
Class average is 85.67

, , .

: Java β„’ ( ),

+1

Sentinel , .

, , , ; , , , , . , , ; , , , .

. Https://en.wikipedia.org/wiki/Sentinel_value.

0

All Articles