java - 如何限制 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 ...
如何限制该循环的结果?
解决方案
假设您希望打印前 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(" ...");
}
推荐阅读
- git-bash - Git Bash如何在终端执行命令后删除空行
- r - 如何使用 R、stringr 等动态删除或替换字符串中具有不确定数字的单词?
- php - 如何在获取时从获取mysql中乘以值
- asp.net - 页面索引在第二页以后不起作用
- mysql - 将手动分配的 ID 重置为自动递增
- c# - Webdriver Driver Mananger 2.7.0 没有从 Nuget 与 .Net 框架 4.5 安装
- laravel - Laravel 5.8 创建递归集合
- haskell - Haskell 中的布尔非穷举模式
- alexa - 在 Alexa 中更改 SessionEndedRequest 处理程序响应
- node.js - 如何从调用的 API 获取集合名称