开发者

How to delete entry in an Address Book program using Java?

I am having trouble with the logic of deleting an entry in an Address Book... I am saving all the entries using an ARRAY.

I am try to make the array[i] = null, if array[i] is equals to the entered name of the user. But after i delete an entry and then try to view all entries again, nothing shows.. and output says :

Exception in thread "main" java.lang.NullPointerException

at AddressBook.viewAll(AddressBook.java:61)

at AddressBook.main(AddressBook开发者_如何学编程.java:35)

Java Result: 1

this is my code in deleting an Entry:

public void deleteEntry() {
        SName = JOptionPane.showInputDialog("Enter Name to delete: ");
        for (int i = 0; i < counter; i++) {
            if (entry[i].getName().equals(SName)) {
                //JOptionPane.showMessageDialog(null, "Found!");
                entry[i] = null;
            }
        }
    }

Can you help me figure out what was wrong with my code... or LOGICAL ERROR?

If you have any suggestion or better way to delete an entry that would be a big help..

please help...


if (entry[i].getName().equals(SName)) {

if on one pass you make

entry[i] = null

then how would you getName() afterwords?

try adding a null check to your if statement

if (entry[i] != null && entry[i].getName().equals(SName)) {

EDIT: Benjamin brings up a good point. You should be prepared for a null result from showinputdialog(). For example, there's a cancel button right? If they press that, you'll get null I believe. Here's some better code for that case:

public void deleteEntry() {
    /* get the input */
    SName = JOptionPane.showInputDialog("Enter Name to delete: ");
    /* if no input, nothing to delete */
    if(SName == null) return;
    /* find the name */
    for (int i = 0; i < counter; i++) {
        /* make sure we have an entry*/
                                /* we know SName is not null */
        if (entry[i] != null && SName.equals(entry[i].getName())) {
            /* null out the deleted entry */
            entry[i] = null;
            // break; /* If you know you have unique names, you can leave the for loop now */
        } /* end if */
    } /* end for i*/
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜