I'm trying to check whether an array of objects contain a specific string.
This is the constructor I have for Product object:
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. 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.
1 Answer 1
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. you cant just compare an object with a string without accessing the String.
solution:
create a getter method in your Product class
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
for(int i = 0; i < current_size_product; i++)
{
if(product[i].getName().contains(string))
//true
}
-
Thank you, I was able to solve the problem using your advice :)Cale– Cale06/06/2014 04:28:18Commented Jun 6, 2014 at 4:28
-
1Note that
getName()
is technically unnecessary. It's not required for your program to run; you can just useproduct[i].name
ifname
is public. "Getter methods" help make it easier to develop large programs with less bugs, but they are not absolute requirements.Stack Exchange Broke The Law– Stack Exchange Broke The Law06/06/2014 04:46:17Commented Jun 6, 2014 at 4:46 -
@immibis it is OOP you need to encapsulate your data.Rod_Algonquin– Rod_Algonquin06/06/2014 04:48:35Commented Jun 6, 2014 at 4:48
-
It is not OOP, it is basic Java programming. When you know how to program, then you can learn OOP design principles.Stack Exchange Broke The Law– Stack Exchange Broke The Law06/06/2014 04:53:40Commented Jun 6, 2014 at 4:53
-
1Then do use a getter of course. I had no way of knowing that from your question and I guessed wrong.Stack Exchange Broke The Law– Stack Exchange Broke The Law06/06/2014 05:13:58Commented Jun 6, 2014 at 5:13
Class<?> [] = new Class<?>[] { Object.class, Integer.class, System.class };
. You've just got an array of Objects.