0
Array object
Suppose I am having two arrays: product[]p=new product[10]; //In this I am storing objects of a product with their names. String[]order=new String [3]; Now I want to check whether the product that I ordered is available in the array product. For example the compiler is running through a loop: if(product[index].name==order[index])//Is this code correct??
5 Réponses
+ 3
Maybe better use string `equals` method, it's what people use to check for testing string content equality.
if(product[index].name.equals(order[index]))
Note that the comparison is case sensitive.
And you should probably use a different index variable for <product> array and <order> array. These arrays have different number of elements.
+ 3
A simple answer would be, before the inner for loop initialize a count variable with value 0.
Inside if condition make count++.
Outside the inner for loop you can do-
if (count==0){
System.out.println("Not Found");
}
+ 2
Use equalsIgnoreCase.
Rest Ipang explained clearly.
+ 1
Thank you Avinesh
0
Order[]m={"bread","butter","cheese"};
product[]p=new product[10];
Suppose in the array p we have bread and butter. Cheese is not stored.
for(int i=0;i<m.length;i++)
{
for(int j=0;j<p.length;j++)
{
if(order[i].equals(p[j].name)
{
//If the product is found
}
}
}
How can I print "not found" only once if the product "cheese" is not stored in the array product?