首页 > 解决方案 > 如何限制 while (iterator.hasNext()) 迭代?

问题描述

我正在使用 Generex 库开发 Java,以针对给定的正则表达式打印字符串

一些 R.E 可以生成无限字符串,我只想处理它们,但还不能。我的代码看起来像;

Generex generex = new Generex(regex);
Iterator iterator = generex.iterator();
    System.out.println("Possible strings against the given Regular Expression;\n");
    while (iterator.hasNext()) {
        System.out.print(iterator.next() + " ");
    }

如果我输入 (a)* 作为正则表达式,输出应如下所示

a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa ...

如何限制该循环的结果?

标签: javanetbeanswhile-loopinfinite-loop

解决方案


假设您希望打印前 8 个项目,"..."如果还有更多要打印的项目,则添加。你可以这样做:

int limit = 8;
int current = 0;
while (iterator.hasNext()) {
    if (current != 0) {
        System.out.print(" ");
    }
    System.out.print(iterator.next());
    // If we reach the limit on the number of items that we print,
    // break out of the loop:
    if (++current == limit) {
        break;
    }
}
// When we exit the loop on break, iterator has more items to offer.
// In this case we should print an additional "..." at the end
if (iterator.hasNext()) {
    System.out.print(" ...");
}

推荐阅读