Java: Confusing while loop

  • Java
  • Thread starter genu
  • Start date
  • #1
22
0
Code:
	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
 

Answers and Replies

  • #2
DavidSnider
Gold Member
494
135
Use a debugger. Set a breakpoint on that line and inspect what the values for person.lastName and lastNameSearch are.
 
  • #3
22
0
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:
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;
	}
 
  • #4
907
2
Just do "while(current != null)" and move the assignment to "person" between the while and the if.
 
  • #5
22
0
great..thx. That solved it >)
 

Related Threads on Java: Confusing while loop

Replies
8
Views
2K
  • Last Post
Replies
6
Views
2K
  • Last Post
Replies
2
Views
2K
Replies
2
Views
862
  • Last Post
Replies
11
Views
947
  • Last Post
2
Replies
26
Views
4K
  • Last Post
Replies
2
Views
5K
  • Last Post
Replies
15
Views
4K
Replies
1
Views
1K
Top