简体   繁体   English

在while循环中使用扫描仪时,如何“灌注”一个循环并创建一个标记?

[英]How do I “prime” a loop and create a sentinel while using scanner in a while loop?

// 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();
}

I am confused about this. 我对此感到困惑。 What would I insert in the while and inside the body and make a sentinel of -1? 我会在身体的内部和内部插入什么,并使前哨为-1? Also what is the appropriate conditional to be placed in the while loop? 另外,放置在while循环中的适当条件是什么? So how would I answer the question of "Add the conditional to the loop so it continues as long as num is not equal to the sentinel"? 那么我将如何回答“将条件添加到循环中,只要num不等于前哨,它就继续进行”的问题?

Does this work for you? 这对您有用吗?

int sentinel = -1;

while(num != sentinel)
{
   // process data
   num = keyboard.nextInt();
}

Use a do..while 使用do..while

int num = -1;
do {
    // process data 
    num = keyboard.nextInt(); 
} while(num != -1);

I would use something like this 我会用这样的东西

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
}

To avoid checking if num has reached the sentinel value both in the while condition and again inside the loop before using num , use break with an infinite loop. 为了避免在使用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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM