Reputation: 8935
I am trying to loop on an object, until a condition is met.
For example:
Input input = new inputFile(fileName);
input.nextMove(); // returns the next line - EOF returns null
So I want to do something like:
for (int[] move = input.nextMove(); move != null) {
System.out.println(Arrays.toString(move));
}
I.E. loop until the end of file.
Question
What's the best way to loop over the object?
Upvotes: 2
Views: 101
Reputation: 49606
It's a typical Iterator
pattern
while(iterator.hasNext()) {
T element = iterator.next();
}
which, for your case, can be adjusted to
int[] move;
while((move = input.nextMove()) != null) {
System.out.println(Arrays.toString(move));
}
Upvotes: 4
Reputation: 22967
Well, you could do
int[] line;
while ((line = input.nextMove()) != null) { ... }
assuming that nextMove()
returns an int[]
.
This construct assigns the result of nextMove()
to line
, which is then available in the while
body. You see here that such an assignment can be used as value-producing expression, and hence this can be compared. In this case, the loop breaks if line
is null
.
Upvotes: 0