I'm searching for an exact value of a node in my Doubly LinkedList using the searchByName method. It doesn't show the data that I want even If I pass a value that is present in the LinkedList.
public void searchByName(String param) throws Exception{
Node currentNode = start;
String theFirstName = currentNode.firstName.toLowerCase();
String theLastName = currentNode.lastName.toLowerCase();
param = param.toLowerCase();
if (start == null) {
throw new Exception("List Underflow");
}else{
String id= "Student ID", ln="Last Name", fn="First Name", course="Course", section="Section", yl="Year Level";
System.out.format("%-10s\t%-10s\t%-10s\t%-5s\t%-10s\t%s", id, ln, fn, course, section, yl);
System.out.println();
while(currentNode.next != null){
if (param == theFirstName || param == theLastName) {
System.out.format("%-10s\t%-10s\t%-10s\t%-5s\t%-15s\t%d", currentNode.studentID, currentNode.lastName, currentNode.firstName, currentNode.course, currentNode.section, currentNode.yearLevel);
System.out.println();
}else{
System.out.println("Not found");
break;
}
currentNode = currentNode.next;
}
if (currentNode.next == null){
System.out.format("%-10s\t%-10s\t%-10s\t%-5s\t%-15s\t%d", currentNode.studentID, currentNode.lastName, currentNode.firstName, currentNode.course, currentNode.section, currentNode.yearLevel);
System.out.println();
}
}
My main function:
public static void main(String[] args) throws Exception {
StudentRecord senators = new StudentRecord();
senators.insertEnd("110007", "Lacson", "Ping", "BSCS", "BSCS-III-A", "Active", 3);
senators.insertEnd("110008", "Angara", "Sonny", "BSCS", "BSCS-III-B", "InActive", 3);
senators.searchByName("Lacson");
}
Link to gist: https://gist.github.com/30b27d3612f95fc2ced99f50c4f23c14
CodePudding user response:
You are not updating theFirstName and theLastName when changing nodes.
Also, compare strings with equals, not ==.
CodePudding user response:
You have many bugs in your method 2 major ones:
- Strings should be compared with equals method not ==
- Your algorithm to traverse the list is wrong
- Always use your own exception (LinkedListOutOfBoundsException)
- Do not modify input parameters inside the function
- Unnecessary else statement since it throws.
- The last if is absolutely useless.
- Try to use a logger
public void searchByName(String param) throws LinkedListOutOfBoundsException {
if (null == start) {
throw new LinkedListOutOfBoundsException("List Underflow");
}
if (null == param) {
throw new IllegalArgumentException("param must not be null");
}
Node currentNode = start;
while (currentNode != null) {
if (param.equalsIgnoreCase(currentNode.firstName)
|| param.equalsIgnoreCase(currentNode.lastName)) {
break;
}
currentNode = currentNode.next;
}
if (null == currentNode) {
LOGGER.info("Not found");
} else {
LOGGER.info("Found {}", param);
}
}