Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

linear search

  Asked By: Charlie    Date: Jun 12    Category: Java    Views: 1095
  


I have created a String
array[productName]that contains a list of appliance names[read into the
array from a file] I have another array that contains a
list of customer records. I have set the
currentCustRecord.product as the target that I am searching for in the
productName array.. But when I do a search, it returns
"target not found". When I try to print out the
productName array[in the search method to see if the values
are being passed], it contains null values. Could
someone give me an idea as to what I am doing wrong? Part
of my code reads: public void
makeProductArray() { currentApplianceRecord = new
Appliance(productFile.readLine()); while(productFile.moreData()) {
productName[0] =
currentApplianceRecord.product; currentApplianceRecord = new
Appliance(productFile.readLine()); } }/* end
makeProductArray*/ public void
makeCustArray() { currentCustRecord = new
Customer(orderFile.readLine()); while(orderFile.moreData()) {
order[0] = currentCustRecord; prod =
currentCustRecord.product; currentCustRecord = new
Customer(orderFile.readLine()); int
where = search( productName, prod); if ( where
>= 0 ) System.out.println("Target found in
index " + where ); else
System.out.println("Target not found" ); }}/* end
makeCustArray*/ public static int search( String array[], String
target ) { for ( int j= 0; j < array.length;
j++ ) if ( array[j] != null ) if (
array[j].equals( target ) ) return j ; // Target found.
return -1 ; // Target not found }

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Perdita Lopez     Answered On: Jun 12

When you put your product
name into the array, you are never incrementing the
array index. If that is your code, it is always "0".
You need to have an index to increment. The same
thing is happening when you fill your "order"
array.<br><br>If you have an IDE with a "debugger", step through
the code  as it goes through the loop and see the
values of the variables as they change.<br><br>Stephen
McConnell<br>http://www.crosslogic.com

 
Didn't find what you were looking for? Find more on linear search Or get search suggestion and latest updates.




Tagged: