Here is another wrapper based solution, but this one has only one internal scanner. I left the other up to show one solution, this is a different, and probably better solution. Again, this solution doesn't implement everything (and is untested), but you will only have to implement those parts that you intend to use.
In this version you would keep around a reference to what the next()
actually is.
import java.util.Scanner;
public class PeekableScanner
{
private Scanner scan;
private String next;
public PeekableScanner( String source )
{
scan = new Scanner( source );
next = (scan.hasNext() ? scan.next() : null);
}
public boolean hasNext()
{
return (next != null);
}
public String next()
{
String current = next;
next = (scan.hasNext() ? scan.next() : null);
return current;
}
public String peek()
{
return next;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…