gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:51:01 26 4
gpt4 key购买 nike

我正在使用 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 ...

如何限制该循环的结果?

最佳答案

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

关于java - 如何限制 while (iterator.hasNext()) 迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50090742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com