Cal*_*ale 2 java arrays class object
我正在尝试检查对象数组是否包含特定字符串。
这是我为 Product 对象提供的构造函数:
public Product()
{
name = "No name yet";
demandRate = 0;
setupCost = 0;
unitCost = 0;
inventoryCost = 0;
sellingPrice = 0;
}
Run Code Online (Sandbox Code Playgroud)
这是数组的初始化:
Product[] product = new Product[3];
Run Code Online (Sandbox Code Playgroud)
我在这里发现了类似的问题 Checking if long is in array和 这里Look if an array has a specified object。所以我尝试了这段代码:
public boolean isAProduct(String nameOfProduct)
//Returns true if a name has been found otherwise returns false
{
boolean found = false;
int counter = 0;
while (!found && (counter < MAXNUMBEROFPRODUCTS))
{
if (Arrays.asList(product).contains(nameOfProduct))
{
found = true;
}
else
{
counter++;
}
}
return found;
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为它允许我为产品输入相同的名称两次。所以我的问题是,我正在尝试的事情可能吗?如果没有,我该如何解决这个问题?
任何建议将不胜感激。
您需要在类中为您的产品名称创建一个 get 方法Product,以便您能够获取要在数组的每次迭代中检查的数据。您不能只将对象与字符串进行比较而不访问字符串。
解决方案:
在您的 Product 类中创建一个 getter 方法
public String getName()
{
return this.name;
}
Run Code Online (Sandbox Code Playgroud)
迭代所有 Product 类并通过调用产品名称的 getter 方法来比较字符串
for(int i = 0; i < current_size_product; i++)
{
if(product[i].getName().contains(string))
//true
}
Run Code Online (Sandbox Code Playgroud)