PDA

View Full Version : LinkedList Problem: reading a variable from an object on a Linked List


AtreideS
09-28-2003, 04:08 AM
I'm having a bit of trouble with a Linked List of objects. I have a Linked List (using Java's built in Linked List) of fruit objects. Each fruit has a name and a price. in Fruit.java I have a get method for returning the fruit's name.

The code below is a method which takes in a search string, and scans through my LinkedList looking for fruit with the matching name:
public String retrieveByName(String searchString)
{

StringBuffer buf = new StringBuffer("");
int count = 0;
for (int q = 0; q < fruit.size(); q++)
{
if(fruit.get(q) != null)
count++;
}

for(int p = 0; p < count; p++)
{
//PROBLEM AREA
Fruit here = fruit(fruit.get(p));
String str = fruit.getFruitName();
String s = searchString.toLowerCase();
if (str.indexOf (s) != -1)
{
if(str.toLowerCase ().indexOf (s.toLowerCase ()) != -1)
{
buf.append(fruit.get(p) + "\n");
}
}
searchName = buf.toString();
}

return searchName;
}


As you can see by the 2 lines under //PROBLEM AREA, I'm having trouble accessing a method or variable from in the object on the LinkedList. Is there a way to fix the problem? Thankyou for taking the time to help.:)

sicarius
09-29-2003, 01:21 AM
try casting the Object into a Fruit.

Also, it appears as if you are counting the number of objects in your LinkedList using a for loop. Why do this when the size method is available?

AtreideS
09-29-2003, 10:26 PM
Thanks for your help, I've got it working now thanks to you.:)
As for the counting, I was simply reusing a past solution to a problem. Certainly makes sense to change it. Thanks.:)