Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java “我该怎么做?”;素数;在while循环中使用scanner时创建一个循环和哨兵?_Java_While Loop - Fatal编程技术网

Java “我该怎么做?”;素数;在while循环中使用scanner时创建一个循环和哨兵?

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

我对此感到困惑。我应该在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 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
}