AyaZoghby
AyaZoghby

Reputation: 341

using if statement within while breaks the loop in Java

I am new in Java and I have a problem in using if statement within while loop.

I wrote the code as follows:

          while(lexicalizations.hasNext())           
           {
               myObject = lexicalizations.next().getObject();
               language= myObject.getTermLanguage();
               if (language.equals(languageCode)) {
                   System.out.println(lexicalizations.next());

               }                             
           }

However, whenever the if condition is true, the program executes its block and then terminates the while loop. So, the rest of items are not checked out. How could I solve that? Thanks so much.

Cheers, Aya.

Upvotes: 0

Views: 390

Answers (3)

Reimeus
Reimeus

Reputation: 159854

You are moving to the next object in the iterator within if statement block. To avoid this just use myObject and you will 'visit' every object:

while (lexicalizations.hasNext())           
{
   myObject = lexicalizations.next().getObject();
   language= myObject.getTermLanguage();
   if (language.equals(languageCode)) {
      System.out.println(myObject);
   }                             
}

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200266

Each invocation of Iterator.next() moves the iterator to the next element of the collection, therefore you must be very careful not to call this method more than once per iteration. You must save the element into a local variable and work with the variable throughout the loop body.

In order to systematically avoid this kind of pitfalls, always prefer to use the enhanced for loop whenever applicable:

for (String lex : lexicalizations) {
  ... your code uses lex here ...
}

Upvotes: 1

Hot Licks
Hot Licks

Reputation: 47749

Note that when you do that println you "consume" the next element, so if there is only one left there will be zero when you get back to the while.

Upvotes: 0

Related Questions