starwarswii
starwarswii

Reputation: 2417

Remember the position in a Scanner

Here's a simple example explaining the problem I'm having:

public static String nextTwoTokens(Scanner scan) {
    String partOne = scan.next();
    String partTwo = scan.next();
    return partOne+partTwo;
}

This should work just fine, except I don't want to modify the position of the "cursor" in the Scanner with my two .next()'s.

From what I've read, you cannot copy a Scanner object. In that case, how would I "remember" the position of the cursor in the Scanner, and then go back to that location before I return in this method?

If I can't do that, is there a way I can get the source the Scanner is reading from in order to build another Scanner? In this case, if I need to create another Scanner, it is fine that the new Scanner starts at the beginning of the file/inputstream/whatever, as opposed to where the old Scanner's cursor was.

Upvotes: 2

Views: 3329

Answers (2)

user7610
user7610

Reputation: 28879

You can get the position of the last returned token in the stream by using scan.match().end().

(This does not solve OP's problem, but it is a valid answer to the question's title, and it solves my problem.)

Upvotes: 1

Alex K
Alex K

Reputation: 8338

The Scanner class doesn't actually implement the Cloneable interface. You could make a custom .clone() method by implementing the Cloneable interface, but in this case, cloning is not a good idea.

To answer your question, no, you cannot do this. You'd need to find a better way.

Another way to do this could be to create a String[] with the handy .split(delimiter) method! So, you could do something like this:

String s = "This is a test.";
String[] tokens = s.split(" "); //split the string into tokens, cutting at the spaces
for(String token : tokens) {
    System.out.println(token);
}

This should print out

This
is
a
test.

And that way you can just cycle through the String[] to get the next tokens, and return back to your previous spot.

And to answer the question you brought up in the comments, if you want to do something other than a String which doesn't really have a split method, I would recommend just doing this:

Scanner scan = new Scanner(INITIALIZE ME HOWEVER YOU WANT);
ArrayList<String> tokens = new ArrayList<String>();
while(scan.hasNext()) {
    tokens.add(scan.next());
}

Basically, just read everything and create a permanent, navigable set of tokens from it.

That's the best advice I can give. It probably isn't the most efficient way, but it's certainly a surefire way to do it.

Upvotes: 2

Related Questions