简体   繁体   English

Java-检查对象数组是否包含特定字符串

[英]Java - Checking whether an array of objects contains a certain string

I'm trying to check whether an array of objects contain a specific string. 我正在尝试检查对象数组是否包含特定的字符串。

This is the constructor I have for Product object: 这是我用于Product对象的构造函数:

public Product()    
{
    name = "No name yet";
    demandRate = 0;        
    setupCost = 0;
    unitCost = 0;        
    inventoryCost = 0;
    sellingPrice = 0;        
}      

This is the initialisation of the array: 这是数组的初始化:

 Product[] product = new Product[3];

I found similar questions here Checking if long is in array and here Look if an array has an specified object . 我在这里检查数组中是否存在long,在这里是否存在指定对象,也发现了类似的问题。 So I tried this code: 所以我尝试了这段代码:

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;
    }

But this doesn't work as it allows me to enter the same name for a product twice. 但这不起作用,因为它允许我为产品输入两次相同的名称。 So my question is, is what I'm attempting even possible? 所以我的问题是,我正在尝试的可能吗? If not, how could I go about solving the problem? 如果没有,我该如何解决该问题?

Any advice would be greatly appreciated. 任何建议将不胜感激。

You need to create a get method to your name of product inside the Product class to enable you to get the data you want to check on each iteration of the array. 您需要在Product类中为Product名称创建一个get方法,以使您能够获取要在数组的每次迭代中检查的数据。 you cant just compare an object with a string without accessing the String. 您不能仅将对象与字符串进行比较而不访问字符串。

solution: 解:

create a getter method in your Product class 在您的Product类中创建一个getter方法

public String getName()
{
   return this.name;
}

Iterate to all the Product class and compare string by calling the getter method for the name of the product 迭代所有Product类,并通过调用getter方法获取产品名称来比较字符串

for(int i = 0; i < current_size_product; i++)
{
  if(product[i].getName().contains(string))
    //true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM