开发者

Logic of deleting in Java

I cant figure out how to start a method to delete a specific entry stored in an array...

I used to do this:

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

but I was advised not to assign the entry[i] to null because it will ruin my entries...

I have no idea how to code it in another way...

What should I need to do is: I need to delete a specific entry from an array please help...

also... its output was error it says:

Exception in thread "main" java.lang.NullPointerException

at AddressBook.viewAll(AddressBook.java:62)

at AddressBook.main(AddressBook.java:36)

Java Result: 1

This is my code in my main program:

public class AddressBook {

    private AddressBookEntry entry[];
    private int counter;
    private String SName;

    public static void main(String[] args) {
        AddressBook a = new AddressBook();
        a.entry = new AddressBookEntry[100];
        int option = 0;
        while (option != 5) {
            String content = "Choose an Option\n\n"
                    + "[1] Add an Entry\n"
                    + "[2] Delete an Entry\n"
                    + "[3] Update an Entry\n"
                    + "[4] View all Entries\n"
                    + "[5] View Specific Entry\n"
                    + "[6] Exit";
            option = Integer.parseInt(JOptionPane.showInputDialog(content));
            switch (option) {
                case 1:
                    a.addEntry();
                    break;
                case 2:
                    a.deleteEntry();
                    break;
                case 3:
                    a.editEntry();
                    break;
                case 4:
                    a.viewAll();
                    break;
                case 5:
                    a.searchEntry();
                    break;
                case 6:
                    System.exit(1);
                    break;
                default:
                    JOptionPane.showMessageDialog(null, "Invalid Choice!");
            }
        }
    }

    public void addEntry() {
        entry[counter] = new AddressBookEntry();
        entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
        entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
        entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
        entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
        counter++;
    }

    public void viewAll() {
        String addText = "  NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
        for (int i = 0; i < counter; i++) {
            addText = addText + entry[i].getInfo() + "\n";
        }
        JOptionPane.showMessageDialog(null, new JTextArea(addText));
    }

    public void searchEntry() {
        int notfound = 0;
        SName = JOptionPane.showInputDialog("Enter Name to find: ");
        for (int i = 0; i < counter; i++) {
            if (entry[i].getName().equals(SName)) {
                JOptionPane.showMessageDialog(null, entry[i].getInfo2());
                break;
            } else {
                notfound++;
            }
        }
        if (notfound != 0) {
            JOptionPane.showMessageDialog(null, "Name Not Found!");
        }
        notfound = 0;
    }

    public void editEntry() {
        int notfound = 0;
        SName = JOptionPane.showInputDialog("Enter Name to edit: ");
        for (int i = 0; i < counter; i++) {
            if (entry[i].getName().equals(SName)) {
                entry[i] = new AddressBookEntry();
                entry[i].setName(JOptionPane.show开发者_JAVA技巧InputDialog("Enter new name: "));
                entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
                entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
                entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
                break;
            } else {
                notfound++;
            }
        }
        if (notfound != 0) {
            JOptionPane.showMessageDialog(null, "Name Not Found!");
        }
        notfound = 0;
    }

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


Assigning the values to null is going to be the easiest practice. If you're really picky, you could resize the array, but that would be rather pointless. Just keep a separate size counter and decrement it each time you set something to null.

Another reason you're getting a null pointer exception is that you have to consider what's happening when you're replacing values in your array with null but still iterating by counter. You're going to be left with holes in your array upon deletion. The first solution would be to bypass null values altogether, and just shift your array down (somewhat of an expensive operation). The second would be to alter your methods to take those null values into consideration. Example:


public void viewAll() {
    String addText = "  NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
    int nonNull = 0;
    for (int i = 0; i < entry.length; i++) {
       if (entry[i] != null) {
         addText = addText + entry[i].getInfo() + "\n";
         nonNull++;
       }

if (nonNull == counter) break; } JOptionPane.showMessageDialog(null, new JTextArea(addText));

}

I don't have a compiler on this computer, so consider it more of psuedo-code. But the idea is that the counter is only keeping track of how many non-null values you have in your address book, and that these null values could be in random places of your array. I added the nonNull integer as a local counter to keep track of how many values you've encountered that aren't null (so you aren't forced to run through the entire address book). Then, I added the if statement to ensure that the value at entry[i] isn't a null value (trying to invoke getInfo() on a null value is what's giving you that error). Lastly, I added the if statement to break the loop if you've encountered all of the non-null values you have stored. Hope this helps. (Also it may be worth considering a LinkedList to eliminate the null values all together).

Actually, for simplicity's sake, you probably are much better off using a LinkedList, unless you are required to use an array, since you would need to alter all of your methods to take null spaces in your array into account. Assuming you're familiar with LinkedLists of course.


Arrays are immutable. You can change the value for a particular index in the array but you can't change the array size itself. To "delete", you could do:

myArray[index] = null;

And just treat null values as unset/deleted entries.


Assigning to null (currently what you are doing) is the proper thing to do. That will eliminate the reference to the object at that index and allow it to be garbage collected.


Replace entry[i] = null; with this:

System.arraycopy(entry, i + 1, entry, i, counter - i - 1);
--counter;
entry[counter] = null; // optional; helps with garbage collection
--i; // required to not skip the next element

(I'm assuming here that counter is the number of valid entries in entry. This will leave no null entries among the first counter elements of entry (assuming that there weren't any to start with).

Further thought: If you need the array length to always match the number of valid entries, you'll have to re-allocate the array and copy the values over. Just use arraycopy to copy entries from 0 through i-1 and from i+1 to counter-1 into the new array and then assign it to entry. This isn't particularly efficient and is best avoided if possible.


Better to this is List which has remove() method. But if you really want use Array I recommend you change Array to List and then remove all values, after it you can always change List to Array


import javax.swing.JOptionPane;

public class Test {

    private static User[] entry = new User[] { new User("Gil"),
            new User("Bil"), new User("John") };

    public static void main(String... args) {
        final Test test = new Test();
        test.deleteEntry();
        for (int index = 0; index < entry.length; index++) {
            User user = entry[index];
        if (user != null)
System.out.println(entry[index]);
        }

    }

    public void deleteEntry() {

        String SName = JOptionPane.showInputDialog("Enter Name to delete: ");
        for (int index = 0; index < entry.length; index++) {
            if (entry[index].getName().equals(SName)) {
                JOptionPane.showMessageDialog(null, "Found!");
                entry[index] = null;
                break;
            }
        }
    }

    private static class User {
        private String name;

        public User(String name) {
            this.name = name;
        }

        /**
         * @return the name
         */
        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return name;
        }

    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜