簡體   English   中英

將foreach循環轉換為while循環

[英]Converting foreach loop to a while loop

所以這是我需要幫助轉換的循環:

public Product findProduct(int id) {

    Product found = null;
    for(Product m : stock){
        if(m.getID() == id){
            found = m;
        }
    }
    return found;
}

它應該在庫存集合中搜索(我剛剛開始學習,所以我對這些術語不太了解),以查找具有與在方法中輸入的int值相同的ID字段的Product對象。 我有一個while循環的想法,我想我有點理解。 我沒有得到的是我應該如何在那里獲得m.getID()的值,Product類中的ID字段。 該類不允許具有import.java.util.Iterator

相當簡單,這意味着返回的Product對象(如果不為null)將具有可通過getID()方法訪問的id值:

public Product findProduct(int id) {

    for(Product m : stock) {
        if(m.getID() == id){
            return m;
        }
    }
    return null;
}
Product found = null;
int counter = 0;
while(counter < stock.size())
{
   if(stock.get(i).getID() == id)
   {
       found = stock.get(i).getID();
       break;
   }
   counter++;
}

這將使用while循環循環遍歷您的列表,如果找到一個元素,則退出循環。 打破; 用於在找到元素時跳出循環。 查看while循環的語法,並嘗試弄清楚它是如何工作的。

如果要使用while循環,請使用get(...)方法遍歷每一項:

public Product findProduct(int id) {
    int counter = 0;
    while(counter < stock.size())
    {
       if(stock.get(counter) != null && stock.get(counter).getID() == id)
           return stock.get(counter);
       counter++;
    }
    return null;
}

使用.get(...)方法時,請確保進行null檢查。

for循環的替代選項:

public Product findProduct(int id) {
    for(int i = 0; i< stock.size(); i++)
       if(stock.get(i) != null && stock.get(i).getID() == id)
           return stock.get(i);

    return null;
}

注意 :根據Product類的編寫方式,您可能需要在此處使用.equals(...)而不是==

然后,當您調用該方法時:

int id = //whatever
Product product = findProduct(id);

int newId;
if(product != null)
    newId = product.getID();//should be same as id

暫無
暫無

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

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