Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java: Confusing while loop

  1. Nov 9, 2009 #1
    Code (Text):

        public boolean search (String lastNameSearch) {
            LinkedListNode<T> current;
           
            current = first;
            boolean found = false;
            ExtPerson person = (ExtPerson) first.info;
           
            while (current.link != null) {
               
                if ((person.lastName.toLowerCase().equals(lastNameSearch.toLowerCase()))) {
                    found = true;
                    System.out.println("I FOUND IT"); // NEVER REACHED because the condition is always false
                    break;
                } else {
                    current = current.link;
                    person = (ExtPerson) current.info;
                }
                System.out.println(person.lastName.toLowerCase().equals(lastNameSearch.toLowerCase())); //RETURNS "true"
            }
           
            return found;
        }
     
    a little more specific:

    http://i37.tinypic.com/2qsbfqt.png
     
  2. jcsd
  3. Nov 9, 2009 #2

    DavidSnider

    User Avatar
    Gold Member

    Use a debugger. Set a breakpoint on that line and inspect what the values for person.lastName and lastNameSearch are.
     
  4. Nov 9, 2009 #3
    thanks, well it seems that it doesn't find items that are in the last node. How can I make it search the last node as well in this loop? or do I have to compare the input to the last node separately?

    Code (Text):

    public boolean search (String lastNameSearch) {
            LinkedListNode<T> current;
           
            boolean found;
            current = first;
            found = false;
            ExtPerson person = (ExtPerson) first.info;
               
            while (current.link != null && !found) {
                if ((person.lastName.toLowerCase().equals(lastNameSearch.toLowerCase()))) {
                    found = true;
                } else {
                    current = current.link;
                    person = (ExtPerson) current.info;
                }
                count++;
            }
           
            return found;
        }
     
     
  5. Nov 9, 2009 #4
    Just do "while(current != null)" and move the assignment to "person" between the while and the if.
     
  6. Nov 9, 2009 #5
    great..thx. That solved it >)
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java: Confusing while loop
  1. C while loop issue (Replies: 26)

  2. Do while loop (Replies: 6)

Loading...