gpt4 book ai didi

java - 如何使用 while 循环在 java 中创建搜索语句并在找到对象时停止并返回该对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:01 26 4
gpt4 key购买 nike

我一直受困于这个 java 搜索语句。我正在尝试搜索一个名为 stock 的产品数组,该数组在 Stockmanager 类中初始化,其中包含 id 字段、名称和库存水平。这些产品对象是在一个名为 Product 的单独类中制作的。

构造函数 Stockmanager:

// A list of the products.
private ArrayList<Product> stock;

/**

* Initialise the stock manager.

*/
public StockManager()
{
stock = new ArrayList<>();
}

产品构造函数:

// An identifying number for this product.
private int id;
// The name of this product.
private String name;
// The quantity of this product in stock.
private int quantity;

/**
* Constructor for objects of class Product.
* The initial stock quantity is zero.
* @param id The product's identifying number.
* @param name The product's name.
*/
public Product(int id, String name)
{
this.id = id;
this.name = name;
quantity = 0;
}

Product 中有一个访问器方法来检索产品对象 ID:

/**
* @return The product's id.
*/
public int getID()
{
return id;
}

现在在 Stockmanager 中,我有我的搜索方法,但如果我不使用我的 for-each 循环,这个方法似乎会提示不兼容的数据类型,或者如果我使用 for-每个循环。

方法:

/**

* Try to find a product in the stock with the given id.

* @return The identified product, or null if there is none

* with a matching ID.

*/
public Product findProduct(int id)
{
int index = 0;
boolean searching = true;

for (Product item : stock)
{
while(searching && index < stock.size())
{
if (item.getID() == id)
{
searching = false;
return item;
} else {
index++;
}
if(searching)
{
return null;
} else {
return item;
}
}
}
}

在这个 return 语句中必须有一个 while 循环,因为如果找到命中,我不需要该方法在数组中进一步查找。请问,我做错了什么?

最佳答案

没有理由要有两个嵌套循环,您也不需要 indexsearching 变量。

您只需要一个for 循环。如果找到匹配的 Product,则将其退回。如果不是,则在循环结束时返回 null

public Product findProduct(int id)
{
for (Product item : stock) {
if (item.getID() == id) {
return item;
}
}
return null;
}

关于java - 如何使用 while 循环在 java 中创建搜索语句并在找到对象时停止并返回该对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com