本文介绍了我怎么“偷看” 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.

提前感谢。

推荐答案

参见答案提供了更有效的解决方案。

See this answer for a more efficient solution.

这是一个非常难看的解决方案,但你可以创建一个包装类扫描程序,它保留两个内部 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上的下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:53