I am trying to create a queue of tokens from a file and I have the following;

Scanner pScanner = new Scanner (System.in);
String ptoken;
While ((tak = tz.getNext()) !=null)
  System.out.println ("The next token is " + tak);
  .......//more code

This works becuase it scans every token, however when I add or delete a token it skips the next token that the above println showed and adds the next token. Can someone please help me?

10 Years
Discussion Span
Last Post by orko

it is very obvious and common problem.... see following thing:
loop yourObject
1 firstObj
2 secObj
3 thirdObj
suppose you have deleted secObj, then thirdObj will come to the place of secObj, and you are going to next loop, which will actually call the next object of thirdObj... In this way, you are definitely going to miss one object.
You can point back to your second positioned thirdObj before running the loops if you have deleted secObj, or can skip incrementing while you remove any object.


Also, when looping a collection for deletion it's easier to loop from end to beginning, i.e. from size()-1 to 0. Element shifts from deletion won't affect your indexing if you do that.


Just to mention in my example, it is true for this certain problem where you are using next() to get the next element (i.e. nodelist).... for array the above code should work.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.