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

How do I quot;peekquot; the next element on a Java Scanner?(我如何“偷看?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 的下一个元素?

基础教程推荐