我如何“偷看"?Java Scanner 的下一个元素?

2022-01-10 00:00:00 iterator java

也就是说,如何在不移除迭代器的情况下获取下一个元素?因为我可能想也可能不想删除它,具体取决于它的内容.我有一个文件扫描器,我在其中使用 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;
    }
}

相关文章