Java “我该怎么做?”;素数;在while循环中使用scanner时创建一个循环和哨兵?
我对此感到困惑。我应该在while和身体内部插入什么,使-1成为哨兵?另外,while循环中要放置的适当条件是什么?那么,我该如何回答“将条件添加到循环中,这样只要num不等于sentinel,循环就会继续”的问题呢Java “我该怎么做?”;素数;在while循环中使用scanner时创建一个循环和哨兵?,java,while-loop,Java,While Loop,我对此感到困惑。我应该在while和身体内部插入什么,使-1成为哨兵?另外,while循环中要放置的适当条件是什么?那么,我该如何回答“将条件添加到循环中,这样只要num不等于sentinel,循环就会继续”的问题呢 // 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
// 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();
}
使用
do..while
int sentinel = -1;
while(num != sentinel)
{
// process data
num = keyboard.nextInt();
}
我会用这样的东西
int num = -1;
do {
// process data
num = keyboard.nextInt();
} while(num != -1);
为避免检查
num
是否在while
条件下以及在使用num
之前再次在循环内达到sentinel值,请使用无限循环的break
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
}
Scanner keyboard = new Scanner(System.in); //data will be entered thru keyboard
for (;;) {
num = keyboard.nextInt();
if (num == -1) {
break;
}
// use num
}