I'm making a linked list of entry's in a Phone book. However I'm struggling to work out a complete delete method. I'm trying to detect the entry I'm trying to delete is not in the list, and give an 'Entry not found' message. I'm using the list interface for linked list. Here is the delete method so far. Now I've tried to cover the "last node" situation in the last if statement. But it doesn't work. If i was not using the list interface I guess I could use the getLast() method and compare it to the entry I'm currently on, but i'd prefer to do it this way and figure out another way to solve it. Any ideas ? --edit the reason its not working is if I delete the last entry on the list, it print out the entry not found message even if the entry was there as the last node and was successfully deleted

 public void deleteEntry(String number) {
    ListIterator<Entry> i = phoneBook.listIterator();

    while(i.hasNext()){
        Entry e = i.next();
        if(e.getNumber().equals(number)){
            i.remove();
            break;
        }
    }
    if(phoneBook.size() != 0 && (!(i.hasNext()))){
        System.out.println("Entry not found");
    }
}
有帮助吗?

解决方案

You may do it this way:

public void deleteEntry(String number) {
    int size = phoneBook.size();
    for (ListIterator<Entry> i = phoneBook.listIterator(); i.hasNext(); ) {
        Entry e = i.next();
        if (e.getNumber().equals(number)) {
            i.remove();
            break;
        }
    }
    if (phoneBook.size() == size) {
        System.out.println("Entry not found");
    }
}

其他提示

Replace the break; statement by return;.

public void deleteEntry(String number) {
    ListIterator<Entry> i = phoneBook.listIterator();
    while(i.hasNext()){
        Entry e = i.next();
        if(e.getNumber().equals(number)){
            i.remove();
            return;
        }
    }
    System.out.println("Entry not found");
}

But better change the return type to boolean and return true as soon as the number found, false otherwise at the end

public void deleteEntry(String number) {
    ListIterator<Entry> i = phoneBook.listIterator();
    boolean found = false;
    while(i.hasNext()){


        Entry e = i.next();
        if(e.getNumber().equals(number)){
            if(!found)
        found = true;

            i.remove();
            break;
        }
    }
    if(!found){
        System.out.println("Entry not found");
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top