Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "peek" the next element on a Java Scanner?

Tags:

java

iterator

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.

Thanks in advance.

like image 513
Juan Pablo Santos Avatar asked Nov 26 '10 21:11

Juan Pablo Santos


People also ask

What does next () do in java scanner?

next() method finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

What is has next () in java?

The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.

Is there a next int scanner?

The hasNextInt() method of Java Scanner class is used to check if the next token in this scanner's input can be interpreted as an int value using the nextInt() method. There is two different types of Java hasNextInt() method which can be differentiated depending on its parameter.

Does java have next line scanner?

The hasNextLine() is a method of Java Scanner class which is used to check if there is another line in the input of this scanner. It returns true if it finds another line, otherwise returns false.


2 Answers

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;
    }
}
like image 97
Reese Moore Avatar answered Sep 28 '22 07:09

Reese Moore


I don't think there is a peek-like method, but you can use hasNext(String) to check if the next token is what you are looking for.

like image 36
DanielGibbs Avatar answered Sep 28 '22 09:09

DanielGibbs