How do I quot;peekquot; the next element on a Java Scanner?(我如何“偷看?Java Scanner 的下一个元素?)
问题描述
也就是说,如何在不移除迭代器的情况下获取下一个元素?因为我可能想也可能不想删除它,具体取决于它的内容.我有一个文件扫描器,我在其中使用 Scanner next() 方法迭代 XML 标记.
That is, how do I get the next element of the iterator without removing it? As I may or may not want to remove it depending on its content. I have a file scanner where I iterate over XML tags using the Scanner next() method.
提前致谢.
推荐答案
参见 this 答案是更有效的解决方案.
See this answer for a more efficient solution.
这是一个非常丑陋的解决方案,但是您可以围绕 Scanner
创建一个包装类,它保留两个内部 Scanner
对象.您可以通过将第二个扫描仪放在另一个前面来获得 peek()
功能
This is a very ugly solution, but you can create a wrapper class around Scanner
which keeps two internal Scanner
objects. You can get peek()
functionality by having the second scanner one ahead of the other
这是一个非常基本的解决方案(只是为了让您了解我在说什么)并且没有实现您需要的所有内容(但您只需要实现您将使用的那些部分).(此外,这是未经测试的,因此请谨慎对待).
This is a very basic solution (just to give you an idea of what I'm talking about) and doesn't implement all that you would need (but you would only need to implement those parts you would use). (also, this is untested, so take it with a grain of salt).
import java.util.Scanner;
public class PeekableScanner
{
private Scanner scan1;
private Scanner scan2;
private String next;
public PeekableScanner( String source )
{
scan1 = new Scanner(source);
scan2 = new Scanner(source);
next = scan2.next();
}
public boolean hasNext()
{
return scan1.hasNext();
}
public String next()
{
next = (scan2.hasNext() ? scan2.next() : null);
return scan1.next();
}
public String peek()
{
return next;
}
}
这篇关于我如何“偷看"?Java Scanner 的下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何“偷看"?Java Scanner 的下一个元素?
基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01