簡體   English   中英

在while中使用if語句中斷Java中的循環

[英]using if statement within while breaks the loop in Java

我是Java新手,在while循環中使用if語句時遇到問題。

我寫的代碼如下:

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

               }                             
           }

但是,只要if條件為true,程序就會執行其塊,然后終止while循環。 因此,其余項目未檢出。 我該如何解決? 非常感謝。

干杯,A。

每次調用Iterator.next()將迭代器移到集合的下一個元素,因此必須非常小心,不要在每次迭代中多次調用此方法。 您必須將元素保存到局部變量中,並在整個循環體內使用該變量。

為了系統地避免此類陷阱,請始終在適用的情況下始終使用增強的for循環:

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

請注意,當執行該println時,您將“消耗”下一個元素,因此,如果僅剩一個,則返回while時將為零。

您將移至if語句塊內迭代器中的下一個對象。 為了避免這種情況,只需使用myObject ,您將“訪問”每個對象:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM