0

As part of my studies on java I'm trying to create a search function, which takes in one parameter String key that correlates to a destination of an object Plane.

Before that I create a Queue of 20 Object each with different parameters and am now trying to search by destination.

This is what I have so far:

    public Plane searchDestination(String key)
    {
        Plane current = first;
        while(current.destination != key)
        {
            if(current.next == null)
                return null;
            else
                current = current.next;
        }
        return current;
    }

It returns successful build, but doesn't return an object(s) with matching criteria, I tried adding System.out.println(current); after return current; but compiler throws out an error. I also have a .displayPlane(); function that should display all plane details (and works in other cases), but when I add current.displayPlane(); after my return current; I get an error saying that it is unreachable.

Am I doing the search correctly, or am I missing something out?

Ilja
  • 44,142
  • 92
  • 275
  • 498
  • 8
    Don't use == and != to compare Strings. Use equals. And when you get an error message, READ it, or post it if you can't understand it. It contains the precise explanation of the problem. In that case, the compiler resuses to compile because it knows that the System.out.println can't ever be executed, since the method returns just before. – JB Nizet Nov 02 '13 at 08:05
  • put `System.out.println(current);` before `return current` to test. – Paul Samsotha Nov 02 '13 at 08:05

2 Answers2

2

Replace

while(current.destination != key)

with

while(!current.destination.equals(key))

For any object (like String) comparison, you should always use equals. Don't use == or != as this only compares references for objects. For primitive type data (like int), you can use == or !=

user2864740
  • 60,010
  • 15
  • 145
  • 220
sarwar026
  • 3,821
  • 3
  • 26
  • 37
0

Have you considered using a Map of destinations to Planes.

 Map<String, Plane> destToPlane = new HashMap<String,Plane>();
 if (destToPlane.containsKey(key))
    return destToPlane.get(key);
 else
    System.out.println("Key not in there");
Tony
  • 345
  • 1
  • 4
  • 11