RedHatcc
RedHatcc

Reputation: 3136

Java Scanner - How to return to the last word after using next()

I currently have a If statement that checks to see if the next word in a document equals a certain length. After it returns true, I want it to add that word to an array or string etc. My problem is once I use the next() command, it proceeds to the next value in the document even though I used it in the condition of the If statement. I am somewhat new to Java so I hope this simple click makes sense.

Scanner in1 = new Scanner(inputFile);
String inputString;

while(in1.hasNextLine()){
     if(in1.next().length() == 6){
          inputString = in1.next();
     }
}

Basically I have a file that contains several words, all different lengths on multiple lines. I want to catch the word that has 6 characters in it. The actual while loop and file is more complex, the problem is that it jumps to the next word after it evaluates the If statement. So if it detects that the next word has 6 characters, it loads the following word that comes after it into the variable. Any help or advice is welcome!

Upvotes: 1

Views: 2336

Answers (2)

templatetypedef
templatetypedef

Reputation: 372992

You can split this loop up into two pieces:

  1. Get the next token and store it, and
  2. Use that cached token.

For example:

while(in1.hasNextLine()) {
     String current = in1.next();
     if(current.length() == 6) {
          inputString = current;
     }
}

This is a standard technique when using iterators or scanners for precisely the reason you've noted - the next() method can't be called multiple times without producing different values.

As an aside, other programming languages have designed their iterators so that getting the value being iterated over and advancing to the next location are separate steps. Notably, the C++ STL considers these to be different operations.

Hope this helps!

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160261

Capture the value of next() into a variable, do the compare, set inputString to that variable. If the length isn't correct, whatever comes next can use the same variable, avoiding additional the extra next(). Not sure if this does what you need it to.

Upvotes: 2

Related Questions