selecting certain strings from a linked list
I have a linkedList using nodes. I have it printing out alphabetically but now I'm trying to print out the people whose names begin with a certain letter that the user ask for. For example: printing out all the people whose names begin with an "A". I'm sure this isn't the best way to do this what I have so far but I'm just trying different things out and I'm pretty new to linked list. Any tips or advice or hints are greatly appreciated.
Heres what I think I have that may be useable:
public void findSameStartingLetter(BigNode front, String letter) {
BigNode curr;
curr = front;
String name;
name = curr.dataitems;
String d;
// char c;
while (curr.next != null){
d = name.substring(0, 1);
if (d.equals(letter)) {
System.out.pr开发者_高级运维intln(d);
curr = curr.next;
// for(int i=0; i < 1; i++) {
// c = letter.charAt(i);
// }
}
}
}
It looks like you need to be reading the name of the person on the node within the loop, rather than reading in the first name and then not assigning that variable again.
You also should be checking to see if the current node is null, not the next one. If you check for the next one, you will miss the last name in the list.
Also, make sure the pointer movement on the list is done outside the if, as we want to check the next node regardless of what the name was.
Aside from the logic, it looks like you are a little uncomfortable with java. To clean up your example you can use the java ability to delare and assign values on one line.
Futhermore, rather than doing a substring and comparing the substring, Java's string has a startWith method that should do the trick as well. Nice job!
public void findSameStartingLetter( BigNode front, String letter )
{
BigNode curr = front;
while( curr != null )
{
String name = curr.dataitems;
if( name.startsWith( letter ) )
{
System.out.println( name );
}
curr = curr.next;
}
}
Looks fine to me, the only thing I'd change is using equalsIgnoreCase()
instead of just equals()
. Oh, and leave the curr = curr.next;
line outside of the if
精彩评论