0

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.showInputDialog("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;
            }
        }
    }
}
4
  • 2
    Who advised you not to assign to null? The only reason you shouldn't, is if you use null to terminate your loops, which would make them terminate prematurely. If you always cycle through the whole list, then null is the best way to do it. Edit: Really it all depends on whether your array should be 1 smaller for removing this element? Commented Feb 18, 2011 at 18:16
  • 3
    Side note: Use a List if you wish to remove an entry and not leave a hole in the collection. Commented Feb 18, 2011 at 18:19
  • If the array is the model in an MVC architecture (very popular in Swing), then having null in the middle of the array is very bad news. Commented Feb 18, 2011 at 18:20
  • guys... can you share me some code... that would be a big help... thanks in advance :) Commented Feb 18, 2011 at 18:23

6 Answers 6

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@Sir Cooper... can you share some code... please... because when i run my posted code it outputs an error saying: Exception in thread "main" java.lang.NullPointerException at AddressBook.viewAll(AddressBook.java:62) at AddressBook.main(AddressBook.java:36) Java Result: 1
See the above edit. Note that the for loop is iterating by the size of the address book rather than the counter.
thank you very much... sir... this deletes a specific entry... thank you so much :)
0

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.

6 Comments

@jeremy i am having problem viewing it... nothing shows each time i deleted a specific entry and then when i view all entries, nothing shows... :( please help thanks again
I don't fully understand. If you delete an entry, you don't want it visible anymore. Also, you're missing your break in the loop when you find the entry to delete. That might have an impact since I don't fully see the rest of the logic.
yes... once i deleted an index in an array.. i want it not to be seen again if i display all the entries, i've also put a break, but still nothing happens... :(
You'll probably need to update your UI to skip over nulls in your array when displaying stuff. Are you refreshing the UI once the data changes? Not seeing more code makes this harder, but I don't expect you to give too much.
hi jeremy.. i've already posted my code... pardon some of my codings... and also... i don't know what happen but when i test my program my edit methods doesn't run properly again :(
|
0

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.

Comments

0

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.

4 Comments

@sir Ted Hopp... what does System.arraycopy do? does it copy the following entry to the one i deleted (like moving the following entry to the deleted array)? Sorry sir... i still don't understand.. i am new at java and still dont know some of the built-in function...
@iama: Here's the description of the function: <download.oracle.com/javase/1.4.2/docs/api/java/lang/…> but it's really nothing you should do. There are data structures that are much more efficient for removing entries in the middle of them - e.g. a linked list.
@iamanapprentice - System.arraycopy does exactly what you guessed: it moves a block of elements from one array to another, or from one place to another in the same array. It's very efficient and is used internally in classes like ArrayList and Vector.
@Voo - there's no reason to avoid System.arraycopy if you're dealing with arrays. Yes, a linked list may be faster to delete a node (once you've found it), but bookkeeping is obnoxious, there's memory overhead, and it's totally unsuitable if you must pass it to an API that requires an array (such as binary search).
0

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

Comments

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

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.