Provide loop conditions that are not Boolean

Viewed 574

I need to accept some positive integers for which I use a for loop as follows:

Scanner in = new Scanner(System.in);
for(int i=0; i<n; i++) { 
    num = in.nextInt(); 
    //do something with num
}

This requires me to (a) know number of integers n beforehand (b) Use a counter i

I know Java does not accept non-Boolean expressions in loop conditions. But how can I do the same without n and i? For example, something like:

while( (num = in.nextInt()) ) {
   //do something with num
}

Any type of loop (for/while/do-while) will do.

4 Answers
Related