如何限制while(iterator.hasNext())迭代?

时间:2018-04-29 20:01:10

标签: java netbeans while-loop infinite-loop

我正在使用Generex库处理Java,根据给定的正则表达式打印字符串

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

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 ...

如何限制该循环的结果?

2 个答案:

答案 0 :(得分:3)

我们假设您要打印前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(" ...");
}

答案 1 :(得分:1)

在你的情况下,我认为字符串的长度比打印的元素数量重要得多,所以我想下面的解决方案可能更好:

Generex generex = new Generex(regex);
Iterator iterator = generex.iterator();
System.out.println("Possible strings against the given Regular Expression;\n");
StringBuilder sb = new StringBuilder();
int limitOfChars = 100; //for example
while (iterator.hasNext()) {
    String next = iterator.next();
    if (sb.length() + next.length() > limitOfChars) break;
    sb.append(next + " ");
}
System.out.println(sb.toString() + " ... ");