【问题标题】:Java - Checking whether an array of objects contains a certain stringJava - 检查对象数组是否包含某个字符串
【发布时间】:2014-07-27 06:13:44
【问题描述】:

我正在尝试检查对象数组是否包含特定字符串。

这是我对 Product 对象的构造函数:

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

这是数组的初始化:

 Product[] product = new Product[3];

我在这里Checking if long is in arrayLook if an array has an 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;
    }

但这不起作用,因为它允许我为产品输入相同的名称两次。所以我的问题是,我正在尝试的可能吗?如果没有,我该如何解决这个问题?

任何建议将不胜感激。

【问题讨论】:

  • 这不是它在 Java 中的工作方式。您需要遍历每个“Product”对象并将“nameOfProduct”与“Product”对象的“name”进行比较。
  • @Nambari 你能提供一个我会如何做的例子吗? :)
  • 我知道你在做课堂作业,所以我不想给你写代码。但是这里是骨架,遍历Product[],得到Product,然后比较这个Product-->“Name”和“nameOfProduct”。
  • 为了将来参考,“类对象数组”的意思类似于Class&lt;?&gt; [] = new Class&lt;?&gt;[] { Object.class, Integer.class, System.class };。你刚刚得到了一个对象数组。

标签: java arrays class object


【解决方案1】:

您需要在 Product 类中为您的产品名称创建一个 get 方法,以使您能够在数组的每次迭代中获取要检查的数据。你不能只比较一个对象和一个字符串而不访问字符串。

解决方案:

在您的 Product 类中创建一个 getter 方法

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

通过调用产品名称的getter方法迭代所有产品类并比较字符串

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

【讨论】:

  • 谢谢您,我能够根据您的建议解决问题 :)
  • 请注意,getName() 在技术上是不必要的。您的程序不需要运行;如果name 是公开的,您可以只使用product[i].name。 “Getter 方法”有助于更轻松地开发具有较少错误的大型程序,但它们不是绝对要求。
  • @immibis 这是您需要封装数据的 OOP。
  • 这不是 OOP,它是基本的 Java 编程。当您知道如何编程时,然后您可以学习 OOP 设计原则。
  • 那么当然要使用吸气剂。我无法从你的问题中知道这一点,我猜错了。
猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
  • 2020-08-11
  • 1970-01-01
  • 2023-03-09
  • 2021-12-19
相关资源
最近更新 更多