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!
You can split this loop up into two pieces:
For example:
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!