Java条件循环

时间:2019-09-23 13:04:44

标签: java loops for-loop while-loop

我试图在对象上循环,直到满足条件为止。

例如:

Input input = new inputFile(fileName);
input.nextMove();  // returns the next line - EOF returns null

所以我想做类似的事情:

for (int[] move = input.nextMove(); move != null) {
    System.out.println(Arrays.toString(move));
}

I.E。循环直到文件末尾。

问题

循环遍历对象的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

这是典型的Iterator模式

while(iterator.hasNext()) {
    T element = iterator.next();
}

根据您的情况,可以调整为

int[] move;
while((move = input.nextMove()) != null) {
    System.out.println(Arrays.toString(move));
}

答案 1 :(得分:0)

好吧,你可以

int[] line;
while ((line = input.nextMove()) != null) { ... }

假设nextMove()返回一个int[]

此构造将nextMove()的结果分配给line,然后在while主体中可用。在这里您可以看到,这样的赋值可以用作产生价值的表达式,因此可以对此进行比较。在这种情况下,如果linenull,则循环会中断。