有人可以向我解释一个哨兵在 Java 中的作用吗?或者它是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21666508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can someone explain to me what a sentinel does in Java? Or how it works?
提问by Oyukyfairy
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
谢谢,麻烦您了!我正在学习如何使用 Java 编码
采纳答案by Tony the Pony
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.
“哨兵”并没有什么特别之处。它只是您选择的任何不是数据集中合法值的常量,因此您可以使用它来标记序列的结尾。例如,如果一个团队的得分永远不会小于零,则可以使用 -999(或任何其他负值)作为中断/结束标记。
Usually, there are better, cleaner ways to do this.
通常,有更好、更干净的方法来做到这一点。
回答by Basheer AL-MOMANI
to understant sentinel-controlled repetition
let's see a simple
example,
为了理解,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
now let's run it
现在让我们运行它
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
In a sentinel-controlled loop, prompts should remind the user of the sentinel. its a good Practice to do
在哨兵控制的循环中,提示应该提醒用户哨兵。这是一个很好的做法
reference: Java? How To Program (Early Objects), Tenth Edition
回答by Manohar Bhat
Sentinel value is used to avoid extra checks inside loops.
哨兵值用于避免循环内的额外检查。
For instance, when searching for a particular value in an unsorted list, every element will be compared against this value, with the loop terminating when equality is found; however to deal with the case that the value should be absent, one must also test after each step for having completed the search unsuccessfully. By appending the value searched for to the end of the list, an unsuccessful search is no longer possible, and no explicit termination test is required in the inner loop; afterwards one must still decide whether a true match was found, but this test needs to be performed only once rather than at each iteration.
例如,在未排序列表中搜索特定值时,每个元素都将与该值进行比较,当找到相等时循环终止;但是为了处理该值应该不存在的情况,还必须在每一步之后测试是否完成了搜索不成功。通过将搜索到的值附加到列表的末尾,不再可能进行不成功的搜索,并且在内循环中不需要显式终止测试;之后仍然必须确定是否找到了真正的匹配项,但是这个测试只需要执行一次,而不是在每次迭代时执行。