Java 中的 Sentinel
在编程上下文中,Sentinel
是用于终止递归或循环算法中的条件的特定值。Sentinel 有多种使用方式,例如虚拟数据、标志数据、胭脂值或信号值。
在 While 循环中使用 Sentinel 值
该程序读取用户的输入并打印出输入数字的乘积。在终止它的 while
循环条件中,如果 number != 0
。这是停止进一步执行循环的 Sentinel。它允许用户知道他们何时完成了输入。
Sentinel
值不是要处理的输入部分。
Sentinel 必须是相似的数据类型,但它应该与正常输入不同。它严格取决于用户对哨兵控制循环应该运行多少次的要求。
他们从用户那里获得输入并使用 Scanner
类。因此,创建了 Scanner
类的对象 input
。
要求用户输入 0 以外的任何数字以继续。但是,为了进一步停止代码的执行,用户必须输入 0。
为了从用户那里获取输入的数字,我们在 input
对象上调用 nextInt()
方法。用户决定循环的执行频率和结束时间。
while
循环从用户接收数字,直到输入数字零。当用户输入零时,程序应生成所有输入数字的乘积。
在哨兵控制的循环中,用户可以在特定条件下退出循环,因为该条件不依赖于计数器。
import java.util.Scanner;
public class SentinelTesting {
public static void main(String [] args){
int enteredNum, numberMultiplied, counter;
counter = 0;
numberMultiplied = 1;
Scanner scannerObj = new Scanner(System.in);
System.out.println("To move ahead, enter a number other than 0");
enteredNum = scannerObj.nextInt();
while (enteredNum != 0) {
numberMultiplied = numberMultiplied*enteredNum;
counter++;
System.out.println("To proceed, enter a number other than 0");
enteredNum = scannerObj.nextInt();
}
System.out.println("The result of multiplying the entered numbers = "+numberMultiplied);
}
}
输出:
To move ahead, enter a number other than 0
10
To proceed, enter a number other than 0
20
To proceed, enter a number other than 0
5
To proceed, enter a number other than 0
0
The result of multiplying the entered numbers = 1000
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。