2014-04-02 89 views
2
// 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就可以繼續添加條件到循環的問題」?如何在一個while循環中使用掃描器時「引發」一個循環並創建一個標記?

回答

1

這是否適合您?

int sentinel = -1; 

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

使用do..while

int num = -1; 
do { 
    // process data 
    num = keyboard.nextInt(); 
} while(num != -1); 
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 
} 
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 
} 
相關問題