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??

13th Dec 2019, 8:11 AM
Preet
5 odpowiedzi
+ 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.
13th Dec 2019, 9:42 AM
Ipang
+ 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"); }
14th Dec 2019, 8:07 AM
Avinesh
Avinesh - avatar
+ 2
Use equalsIgnoreCase. Rest Ipang explained clearly.
13th Dec 2019, 7:03 PM
Avinesh
Avinesh - avatar
+ 1
Thank you Avinesh
14th Dec 2019, 11:43 AM
Preet
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?
14th Dec 2019, 7:35 AM
Preet