如何使用Java删除通讯簿程序中的条目? [英] How to delete entry in an Address Book program using Java?

查看:152
本文介绍了如何使用Java删除通讯簿程序中的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在删除地址簿中的条目时遇到问题...我正在使用ARRAY保存所有条目。

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

我试着如果 array [i] 等于输入的用户名,则使 array [i] = null,。但是在我删除一个条目然后再次尝试查看所有条目之后,没有显示..并且输出显示:

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 :


线程中的异常main AddressBook.viewAll上的java.lang.NullPointerException

(AddressBook.java:61)

AddressBook.main上的
(AddressBook.java:35)

Java结果:1

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;
            }
        }
    }

你能帮我搞清楚吗?我的代码出了什么问题...或者LOGICAL ERROR?

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..

请帮助......

推荐答案

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

如果在一次通过你

entry[i] = null

那你怎么会 getName()后记?

尝试在if语句中添加空检查

try adding a null check to your if statement

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

编辑:本杰明提出了一个很好的观点。你应该为 showinputdialog()的空结果做好准备。例如,有一个取消按钮吗?如果他们按下那个,我相信你会得到零。以下是针对该案例的一些更好的代码:

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*/
}

这篇关于如何使用Java删除通讯簿程序中的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆