// Create a constant sentinel of -1
// “Prime” the loop
// Add the conditional to the loop so it continues
// as long as num is not equal to the sentinel
Scanner keyboard = new Scanner(System.in); //data will be entered thru keyboard
while (...) {
//process data
num = keyboard.nextInt();
}
我对此感到困惑。我会在身体内部和身体内插入什么并制作-1的哨兵?在while循环中放置的适当条件是什么?那么我如何回答"将条件添加到循环中的问题,只要num不等于sentinel"?
答案 0 :(得分:1)
这对你有用吗?
int sentinel = -1;
while(num != sentinel)
{
// process data
num = keyboard.nextInt();
}
答案 1 :(得分:0)
使用do..while
int num = -1;
do {
// process data
num = keyboard.nextInt();
} while(num != -1);
答案 2 :(得分:0)
我会用这样的东西
int num = 0;
while(num != - 1)
{
num = keyboard.nextInt();
// whatever you want to do with num might want to put code in an if like
if(num != -1)
{
//do code
}
//also you could get the number at then end so you can do processing without the if statement above
}
答案 3 :(得分:0)
为了避免在使用num
之前检查while
是否已在num
条件中以及在循环内再次达到标记值,请使用带有无限循环的break
。
Scanner keyboard = new Scanner(System.in); //data will be entered thru keyboard
for (;;) {
num = keyboard.nextInt();
if (num == -1) {
break;
}
// use num
}