Java 将foreach循环转换为while循环
下面是我需要帮助转换的循环:Java 将foreach循环转换为while循环,java,loops,foreach,while-loop,Java,Loops,Foreach,While Loop,下面是我需要帮助转换的循环: public Product findProduct(int id) { Product found = null; for(Product m : stock){ if(m.getID() == id){ found = m; } } return found; } 它应该在stock集合(我刚开始学习,所以我不太了解术语)中搜索与我们在方法中输入的int值具有相同ID字段
public Product findProduct(int id) {
Product found = null;
for(Product m : stock){
if(m.getID() == id){
found = m;
}
}
return found;
}
它应该在stock集合(我刚开始学习,所以我不太了解术语)中搜索与我们在方法中输入的int值具有相同ID字段的Product对象。
我想到了一个while循环,我想我有点理解它。我没有得到的是如何得到m.getID()的值,产品类中的ID字段。
不允许该类具有import.java.util.IteratorProduct found=null;
Product found = null;
int counter = 0;
while(counter < stock.size())
{
if(stock.get(i).getID() == id)
{
found = stock.get(i).getID();
break;
}
counter++;
}
int计数器=0;
while(计数器
这将使用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;
}
public Product findProduct(int id) {
for(Product m : stock) {
if(m.getID() == id){
return m;
}
}
return null;
}
注意:根据产品
类的编写方式,您可能需要在此处使用.equals(…)
而不是=
然后,当您调用该方法时:
int id = //whatever
Product product = findProduct(id);
int newId;
if(product != null)
newId = product.getID();//should be same as id
非常简单,这意味着返回的产品对象(如果它不为null)将具有通过
getID()
方法访问的id
值:
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;
}
public Product findProduct(int id) {
for(Product m : stock) {
if(m.getID() == id){
return m;
}
}
return null;
}
使用iterator.next()时需要强制转换元素。例如:Product m=(Product)productIterator.next()我看不出有什么理由因为这个原因而进行while循环。老实说,我只是把一个
中断在found=m之后的code>in
以避免在已经找到要查找的内容后进行不必要的迭代…..或者在找到匹配项时只返回m,然后在循环完成后返回null,而不是返回find。尽管这是可行的,它与OP已经拥有的东西没有任何区别,也没有解决OP的问题:/OP的问题是什么?我不太清楚。你能解释一下吗?