繁体   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