Link to home
Start Free TrialLog in
Avatar of luna621
luna621

asked on

Applet error display - checking for duplicate items in doubly linked list

Hello,

I'm having problems checking for duplicates.  In my command line (Win-DOS), it'll print "Duplicate ID, can't add.", but in my applet, it doesn't show that in the error message.  Also, duplicate names are suppose to be ok as long as the IDs are different -- they should be added to the list sorted by ID first, then by name.  I think my program is saying dup names are not ok, and so does not add it to the list.

----------------------------------------------------------------------
My codes:
----------------------------------------------------------------------
1. http://www2.hawaii.edu/~flam/DLN.java
2. http://www2.hawaii.edu/~flam/ISortedList.java 
3. http://www2.hawaii.edu/~flam/Person.java
4. http://www2.hawaii.edu/~flam/SortedList.java
5. http://www2.hawaii.edu/~flam/SortedListException.java
6. http://www2.hawaii.edu/~flam/OrderedList.java

Thank you!!

-luna621 =^^=
Avatar of luna621
luna621

ASKER

Avatar of luna621

ASKER

Oh look!  There's an Edit Question link.  Sorry!!
Avatar of luna621

ASKER

Ok, I corrected it.  Now, I'm off to a peaceful place.     -_-  ....zzzzzZZZZ
Avatar of Mayank S
You can show an error-message using JOptionPane.showMessageDialog ().
>> In my command line (Win-DOS), it'll print "Duplicate ID, can't add.", but in my applet, it doesn't show that in the error message.

At the place where you use a System.out.println () to show the message on the console, use a JOptionPane.showMessageDialog (). Its in the javax.swing package.
In SortedLis.java:

>> else if (cmpResult==0) {
>> System.out.println("\nSorry! A Person with this ID already exists!\n");

else if ( cmpResult == 0 ) {
  JOptionPane.showMessageDialog ( <parent-frame>, "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE ) ; // show a warning message

Mayank =^^=

;-)
Pass the Applet as the <parent-frame>. You will need to pass it as an extra parameter somehow to SortedList.java.
But I guess the compareTo () method has to be slightly shaped up. Because you don't return a 0 in all cases where the IDs are the same.
Remark:
The removeAll() function of your SortedList is not used for the moment I guess.
Because you would quickly have a null pointer exception.

Mind the memory leaks!
As I told you before, the Garbage Collector can't clean up objects it they are still referenced.

E.g. Your removePos() function also has this problem:
If you delete the first node of the list, you just replace head, by it's successor and decrement the count. That not enough: You have to reset the link of your current head to the previous head too.

That's why (in some previous posts) I adviced you to have a

           public void remove(DLN node)

I see you added it. But hey, you have to use it too. ;)
Please use it in all your other remove functions.

Now, it takes care of
(1) cleaning up obsolete references
(2) count--

You could also change it to take care of resetting head/tail too (if needed)  (3)
Then you never have to break your head on that again.

That's a main rule of thumb: (try to) break up your code in small pieces you can easily manage.
Pro's :
a) They are simple (because they only perform a small part of the job)
b) Once they are working well (=tested), you can rely on them with your eyes closed:
    That means, you can reuse them where needed without asking if it will work.

Here's the new remove():

public void remove(DLN node) {

        // Reset some links
        if(node.getPrev()!=null) {
            node.getPrev().setNext(node.getNext());                                 // (1)
        } // end if
      else {
          // we're deleting the head, so:
          head = head.getNext();                                                          // (3)
        }

        if(node.getNext()!=null) {
           node.getNext().setPrev(node.getPrev());                                 // (1)
        } // end if
      else {
          // we're deleting the tail, so:
          tail = tail.getPrev();                                                               // (3)
        }

        node.setPrev(null);
        node.setNext(null);
        count--;                                                                                 // (2)
    } // end remove()


Now, look how simple your removePos() function can be written:

    public void removePos(int index) throws SortedListException {
        if (index >= 0 && index <= count) {

            DLN nodeToDelete = find(index);
            remove(nodeToDelete);                                        // takes care of (1), (2) & (3)

        } // end if
        else {
            System.out.println("List index out of bounds exception on remove");
        } // end else
    }   // end removePos()

and your removeAll():

public void removeAll() {
    while(head != null)
        remove(head);   // This "automagically" changes head to the next one
}

I see you also introduced a find() function.

Well, you can use it to increment the performance of your add function:

replace
             DLN nodeTmp = head;
by
             DLN nodeTmp = find(count/2);

[ You remember the idea behind it, don't you? But you had problems because get() returned Comparable. So, since find() doesn't ... ]

And in your remove() function you certainly also have to replace

             DLN nodeTmp = new DLN(get(count/2));

by

             DLN nodeTmp = find(count/2);

Because, you don't have to compare with a new object [ new DLN(get(count/2)); ]
if the object you need [ find(count/2); ] is available

I realize these are no comments on your actual question,
but I think they make your app much better. And that's the goal, isn't it?
Another thing:

in your remove(Comparable item)  function

you have the line

             int cmpResult = nodeTmp.compareTo(item);


That's wrong: you compare a DLN object (nodeTmp) with a Person object (item)

If you really run that you will get a ClassCastException at

public int compareTo(Object obj) {
         DLN node = (DLN)obj;                    <<<<<<<<<<<<<<<<<<<<<<<<<
         return getItem().compareTo(node.getItem());
     } // end compareTo()

because the incoming obj is a Person, and can't be casted to a DLN object.

It should be
                     int cmpResult = nodeTmp.compareTo(nodeToX);

comparing DLN objects

A lot of stuff to think about, huh?
;)

If you have questions about my comments, please ask.
Avatar of luna621

ASKER

Wow, that IS a lot to think about!  Need to let my brain settle for a bit before I post any more comments =^^=
Avatar of luna621

ASKER

You know, I just realized I already had a:

    public Comparable get(int position) throws SortedListException {
        ...
    } // end get()

I think I'm going to rewrite that with the stuff you said about my find().
Avatar of luna621

ASKER

>Comment from zzynx
>Date: 03/30/2004 12:17AM HST
>
>Remark:
>The removeAll() function of your SortedList is not used for the moment I guess.
>Because you would quickly have a null pointer exception.
---------------------------------------------------------------------------------------------
Ok, this is the removeAll() I currently have:

    public void removeAll() {
        while(head != null) {
            //temp = head;  <----------- do I need this?
            head = head.getNext();
            temp.setNext(null);
            //head.setPrev(null);  <----------- do I need this?
            temp = null;
        } // end while

        head = null;
        count = 0; // <-------------- I know this is ok  :)

    } // end removeAll()
Avatar of luna621

ASKER

>Comment from zzynx
>Date: 03/30/2004 12:31AM HST
>
>Another thing:
>
>in your remove(Comparable item)  function
>
>you have the line
>
>             int cmpResult = nodeTmp.compareTo(item);
>
>It should be
>                     int cmpResult = nodeTmp.compareTo(nodeToX);
---------------------------------------------------------------------------
Woopsie!!  I guess I didn't see that.  ^_^''

Okay, I think I'm going to try to use this remove method, and not the removePos method.  Need to update a bit first.
Avatar of luna621

ASKER

>Comment from zzynx
>Date: 03/30/2004 12:17AM HST
>
>Remark:
>The removeAll() function of your SortedList is not used for the moment I guess.
---------------------------------------------------------------------------------------------
I use it in the OrderedList.java, and it seems to work ok...

    public class Ears implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if(whichButton.equals("Clear List")) {
                if(list.isEmpty()==true) {
                    error.setText("Sorry, there are no people in the list.");
                    id.setEditable(false);
                    name.setEditable(false);
                    add.setEnabled(false);
                    removeFirst.setEnabled(false);
                    removeLast.setEnabled(false);
                    clear.setEnabled(false);
                } // end if
                if(list.isEmpty()==false) {
                   list.removeAll(); //<------------------------------- here it is!!!
                   listArea.setText("");
                } // end if
            } // end if
        } // end actionPerformed
    } // end Ears
Avatar of luna621

ASKER

Okay, I'm confusing myself - so I deleted some methods.  Basically, my SortedList.java has:

/**
 * add --- Adds the given item to the list in its correct sorted-order position.
 *         Duplicate items (where x.compareTo(y) == 0) may or may not be suppor-
 *         ted, depending on the implementing class. x comes before y in the list
 *         if x.compareTo(y) < 0.
 *
 * @param item, a java.lang.Comparable object
 * @throws SortedListException if the item cannot be added to the list
 */
    public void add(Comparable item) throws SortedListException {
        ....
    } // end add()

/**
 * get --- Gets the object at the given position in the list.  Does not affect
 *         the state of the list.
 *
 * @param position the position of the item to get
 * @return the object in that position in the list
 * @throws SortedListException  if the object cannot be returned
 *         (such as when position is < 1 or > size())
 */
  public Comparable get(int position) throws SortedListException {
        ....
    } // end get()


/**
 * isEmpty --- Determines whether or not the list is empty.
 *
 * @return false if there are no elements in the list (size() == 0),
 *         otherwise returns true.
 */
    public boolean isEmpty() {
        ....
    } // end isEmpty()


/**
 * remove --- Removes the given item from the list.
 *            Whether all matching items or only one are removed depends on the
 *            implementation.
 *
 * @param item, the java.lang.Comparable object to remove from this list.
 * @throws SortedListException if the object cannot be removed
 *         (such as when the item is not in the list)
 */
    public void remove(Comparable item) throws SortedListException {
        ....
    } // end remove()


/**
 * remove --- Remove the object at the given position in the list.  The given
 *            position must be in the range of the list: 1 <= position <= size()
 *
 * @param position the position to remove from the list
 * @throws SortedListException  if the object cannot be removed
 *         (such as when position is < 1 or > size())
 */
    public void remove(int position) throws SortedListException {
        ....
    } // end remove()


/**
 * removeAll --- Removes all elements from this list.  size() is then 0.
 *
 */
    public void removeAll() {
        ....
    } // end removeAll()


/**
 * size --- Returns the size of the list.
 *
 * @return the number of elements in the list
 */
    public int size() {
        ....
    } // end size()
-------------------------------------------------------------------------
So far, I think everything works EXCEPT the 2 remove methods.  Let me try go through it again with your suggestions.  I'm trying not to add anymore methods than I need, but will add if necessary  :)
Avatar of luna621

ASKER

Ah!  The errors!!

java.lang.ClassCastException
        at Person.compareTo(Person.java:38)
        at DLN.compareTo(DLN.java:67)
        at SortedList.remove(SortedList.java:163)
        at SortedList.remove(SortedList.java:225)

----------------------------------------------------------------------
Updated codes:
----------------------------------------------------------------------
1. http://www2.hawaii.edu/~flam/SortedList.java
2. http://www2.hawaii.edu/~flam/OrderedList.java
Avatar of luna621

ASKER

Okay rewrote:

    public void remove(int position) throws SortedListException {
        if (position >= 0 && position <= count) {
            DLN nodeToDelete = get(position);
            remove(nodeToDelete);
        } // end if
        else {
            System.out.println("List index out of bounds exception on remove");
        } // end else
    } // end remove()
---------------------------------------------------------------------------------------
Gives this error:

found   : java.lang.Comparable
required: DLN
            DLN nodeToDelete = get(position);
                                  ^
1 error

Here's the get method once again:

    public Comparable get(int position) throws SortedListException {
        DLN current = head;
        for (int skip = 0; skip < position; skip++) {
            current = current.getNext();
        } // end for
        return current.getItem();
    } // end get()
Avatar of luna621

ASKER

Sorry, the error should look like this:

            DLN nodeToDelete = get(position);
                                               ^
Avatar of luna621

ASKER

Updated codes:
----------------------------------------------------------------------
1. http://www2.hawaii.edu/~flam/SortedList.java
Avatar of luna621

ASKER

Ok, I just typecasted it:

            DLN nodeToDelete = ((DLN)get(position));
Avatar of luna621

ASKER

Nevermind...

java.lang.ClassCastException
        at SortedList.remove(SortedList.java:222)
Avatar of luna621

ASKER

Okay, changed it back to what I originally had.  And I still get this error:

java.lang.ClassCastException
        at Person.compareTo(Person.java:38)
        at DLN.compareTo(DLN.java:67)
        at SortedList.remove(SortedList.java:154)
        at SortedList.remove(SortedList.java:211)

Is something wrong with my compareTo method?

---------------------------------------------------------
Person.java
---------------------------------------------------------
    public int compareTo(Object object) {
        //typecase to same kind of object
        int iValue = ((Person)object).getID(); // <------------------  at Person.compareTo(Person.java:38)
        //now it is possible to compare
        if(this.getID()<iValue) {
            return -1;
        } // end if
        if(this.getID()>iValue) {
            return 1;
        } // end if
        return 0;
    } // compareTo()

---------------------------------------------------------
DLN.java
---------------------------------------------------------
     public int compareTo(Object obj) {
         DLN node = (DLN)obj;
         return getItem().compareTo(node.getItem()); // <-----------  at DLN.compareTo(DLN.java:67)
     } // end compareTo()

---------------------------------------------------------
SortedList.java
---------------------------------------------------------
    public void remove(Comparable item) throws SortedListException { ;
        if(head==null) { // list is empty, nothing to delete
            System.out.println("Nothing to delete!  List is empty.");
            return;
        } // end if
        DLN nodeToX = new DLN(item); // We make a temporary new DLN object
                                     // for the item we have to delete
        DLN nodeTmp = new DLN(get(count/2));
        int firstCmpResult = nodeTmp.compareTo(nodeToX); // <------------  at SortedList.remove(SortedList.java:154)
        while(true) {
        ...
    } // end remove()


    public void remove(int position) throws SortedListException {
        if(position >= 0 && position <= count) {
            DLN nodeToDelete =  new DLN(get(position));
            remove(nodeToDelete); // <-------------  at SortedList.remove(SortedList.java:211)
        } // end if
        else {
            System.out.println("List index out of bounds exception on remove");
        } // end else
    } // end remove()
Avatar of luna621

ASKER

My getItem in DLN.java is:

     public Comparable getItem() {
         return cItem;
     } // end getItem

And getID in Person.java is:

    public int getID() {
        return this.iID;
    } // END getID()
>> int iValue = ((Person)object).getID();

Perhaps the object passed is not of type Person somehow.

Did you try the JOptionPane for showing the message-boxes?
Avatar of luna621

ASKER

Hmm... is that the same thing as Java Console??  This is what it prints:

Name added.

Count is: 1

Name added.

Count is: 2

Name added.

Count is: 3
java.lang.ClassCastException
      at Person.compareTo(Person.java:38)
      at DLN.compareTo(DLN.java:67)
      at SortedList.remove(SortedList.java:154)
      at SortedList.remove(SortedList.java:212)
      at OrderedList$Ears.actionPerformed(OrderedList.java:269)
      at java.awt.Button.processActionEvent(Unknown Source)
      at java.awt.Button.processEvent(Unknown Source)
      at java.awt.Component.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.run(Unknown Source)
Avatar of luna621

ASKER

   public int compareTo(Object object) {
        //typecase to same kind of object
        Person obj = (Person)object; //<------------------- this seems to be the thing giving me problems...
        int iValue = obj.getID();
        //now it is possible to compare
        if(this.getID()<iValue) {
            return -1;
        } // end if
        if(this.getID()>iValue) {
            return 1;
        } // end if
        return 0;
    } // end compareTo()
>> Hmm... is that the same thing as Java Console??  This is what it prints:

No. JOptionPane is for displaying message-boxes. It should display the stuff in a customized dialog-box.

>> Person obj = (Person)object; //<------------------- this seems to be the thing giving me problems...

Then your object is not of type Person. This problem was not there yesterday, right? How did it come?
Avatar of luna621

ASKER

Where would I access the JOptionPane?

>Then your object is not of type Person. This problem was not there yesterday, right? How did it come?


I think I changed my program according to this comment:

Comment from zzynx
Date: 03/30/2004 12:31AM HST


Another thing:

in your remove(Comparable item)  function

you have the line

             int cmpResult = nodeTmp.compareTo(item);


That's wrong: you compare a DLN object (nodeTmp) with a Person object (item)

If you really run that you will get a ClassCastException at

public int compareTo(Object obj) {
         DLN node = (DLN)obj;                    <<<<<<<<<<<<<<<<<<<<<<<<<
         return getItem().compareTo(node.getItem());
     } // end compareTo()

because the incoming obj is a Person, and can't be casted to a DLN object.

It should be
                     int cmpResult = nodeTmp.compareTo(nodeToX);

comparing DLN objects
>> Where would I access the JOptionPane?

Exactly where you print: System.out.println ( "That ID already exists" ) ; // or something like that -> where you display that the ID is a duplicate

>> I think I changed my program according to this comment

Oh, then I'll have to go through the code again. Can you just try debugging with a few System.out.println () statements in compareTo () ?

Person.java:

public int compareTo(Object object) {
        //typecase to same kind of object
        System.out.println ( object.getClass () ) ; // print the class of object
        Person obj = (Person)object; //<------------------- this seems to be the thing giving me problems...
        int iValue = obj.getID();
        //now it is possible to compare
        if(this.getID()<iValue) {
            return -1;
        } // end if
        if(this.getID()>iValue) {
            return 1;
        } // end if
        return 0;
    } // end compareTo()
Avatar of luna621

ASKER

Ah ha!!  I think I know what it is.  In yesterday's program, I used the methods

    public void removePos(int index) throws SortedListException {
        ....
    } // end removePos()
   public void remove(DLN node) {
        ....
    } // end remove()
   public DLN find(int index) {
        ....
    } // end find()



I never used:

public void remove(Comparable item) throws SortedListException {

That's probably why I never had problems with my program.  

In today's code, I removed all the previously listed remove codes and just used the one I didn't use.

Ok, well, you should not *remove* your methods. You should just comment them (I hope you have done that only).

What's the status now?
Avatar of luna621

ASKER

Oh, I learned that the hard way the other time :)

I saved it as another file.  I just renamed it to the one I'm using for this program, and it works.  It's just that I was hoping to get the:

public void remove(Comparable item) throws SortedListException {
    ...
} // end remove()

to work some how, since my add() is also taking a Comparable item.  The remove() should be similar to the add()... maybe something's wrong with my get().  I was having problems with that.  Hence why I created & am using a find().  Is something wrong with my get()?

    public Comparable get(int position) throws SortedListException {
        DLN current = head;
        for (int skip = 0; skip < position; skip++) {
            current = current.getNext();
        } // end for
        return current.getItem();
    } // end get()
Avatar of luna621

ASKER

Here's the SortedList.java that I'm using now: http://www2.hawaii.edu/~flam/SortedList.java

This is the original SortedList.java: http://www2.hawaii.edu/~flam/SortedList-original.java
Avatar of luna621

ASKER

AAAAHHHHHHHHHHHH!!!!  I figured it out!!!!!  It was

    public void remove(int position) throws SortedListException {
        ...
    } // end remove()


that wasn't calling the right thing!!!
Avatar of luna621

ASKER

Ok, here's the updated code: http://www2.hawaii.edu/~flam/SortedList.java

Yay!  Now I can work on the error display.  I'll be back with more questions soon!

-luna621 =^^=
Avatar of luna621

ASKER

Oh darn!  I forgot to check the Remove Last button.  Okay, I get this error:

java.lang.NullPointerException
        at SortedList.get(SortedList.java:122)
        at SortedList.remove(SortedList.java:225)

    public Comparable get(int position) throws SortedListException {
        DLN current = head;
        for (int skip = 0; skip < position; skip++) {
            current = current.getNext();
        } // end for
        return current.getItem(); //<--------------- at SortedList.get(SortedList.java:122)
    } // end get()


    public void remove(int position) throws SortedListException {
        if (position >= 0 && position <= count) {
            if(position == 0) {
            // delete the first node from the list
            head = head.getNext();
            } // end if
            else {
                DLN prev = (DLN)get(position); //<---------------  at SortedList.remove(SortedList.java:225)
                if(prev == null) {
                    return ;
                } // end if
                // delete the node after the node that prev
                // references, save reference to node
                DLN current = prev.getNext();
                if(current != null) {
                    prev.setNext(current.getNext());
                } // end if
            } // end else
            count--;
        } // end if
        else {
            System.out.println("List index out of bounds exception on remove");
        } // end else
    } // end remove()
Since you're using multiple .java files, make sure your classes don't get mixed up. You should make all your classes public to be on the safe side, since you have only one class in one .java file. Otherwise, you can have a SortedList class in SortedList.java and one SortedList class in SortedList-original.java, and you might compile the second one -> and expect the first one to run :-)
Avatar of luna621

ASKER

I call the Remove Last from the OrderedList.java as:   list.remove(list.size());
Avatar of luna621

ASKER

>Comment from mayankeagle
>Date: 03/30/2004 08:46PM HST

Ooo!!  Good point.  Let me check that now :)
Do you pass list.size () or list.size () - 1 ??
Avatar of luna621

ASKER

Yup, I was using the correct .class file  =^^=

Still getting the NullPointerException though  >_<''
Avatar of luna621

ASKER

Let me try list.size()-1.
Try with size () - 1.
Avatar of luna621

ASKER

java.lang.ClassCastException
        at SortedList.remove(SortedList.java:225)

    public void remove(int position) throws SortedListException {
        if (position >= 0 && position <= count) {
            if(position == 0) {
            // delete the first node from the list
            head = head.getNext();
            } // end if
            else {
                DLN prev = (DLN)get(position); //<------------- at SortedList.remove(SortedList.java:225)
                if(prev == null) {
                    return ;
                } // end if
                // delete the node after the node that prev
                // references, save reference to node
                DLN current = prev.getNext();
                if(current != null) {
                    prev.setNext(current.getNext());
                } // end if
            } // end else
            count--;
        } // end if
        else {
            System.out.println("List index out of bounds exception on remove");
        } // end else
    } // end remove()


Should I write an 'if' statement in there that handles.... ???  Something that'll fix the null pointer?
Avatar of luna621

ASKER

java.lang.ClassCastException

That's strange, since the Remove First works...
Avatar of luna621

ASKER

BTW, I call Remove First like this:   list.remove(0);
Avatar of luna621

ASKER

I checked my counters, and they are counting nicely.  And since:

    public int size() {
        return count;
    } // end size()

that method should be ok...
>> Something that'll fix the null pointer?

Its a ClassCastException, right? Not a NullPointer anymore?

I have a feeling that the classes have been mixed up. Can you just make all of them public and re-compile? That could resolve some issues.
>> BTW, I call Remove First like this:   list.remove(0);

Then removeLast () should be passed size () - 1.
Avatar of luna621

ASKER

ok, I'm going to recompile everything.  Hold on  =^^=
Avatar of luna621

ASKER

Ok, everything is recompiled, but I still get that ClassCastException...
Avatar of luna621

ASKER

That's funny.  When I call it list.remove(list.size()), I get null pointer.  When I call list.remove(list.size()-1), I get ClassCastException.
Avatar of luna621

ASKER

   public void remove(int position) throws SortedListException {
        if (position >= 0 && position <= count) {
            if(position == 0) {
                // delete the first node from the list
                head = head.getNext();
            } // end if
            else {
                DLN prev = (DLN)get(position);
                if(prev == null) {
                    return;
                } // end if
                // delete the node after the node that prev
                // references, save reference to node
                DLN current = prev.getNext();
                if(current != null) {
                    prev.setNext(current.getNext());
                } // end if
            } // end else
            count--;
        } // end if
        else {
            System.out.println("List index out of bounds exception on remove");
        } // end else
    } // end remove()

//-----------------------------------------------------------------
                if(prev == null) {
                    return;
                } // end if

Is that correct?
Avatar of luna621

ASKER

Okay, should be something like:

    public void remove(int position) throws SortedListException {
        if (position >= 0 && position <= count) {
            if(position == 0) {
                // delete the first node from the list
                head = head.getNext();
            } // end if
            else {
                DLN prev = (DLN)get(position);
                if(prev == null) {
                    return;
                } // end if
                // delete the node after the node that prev
                // references, save reference to node
                DLN current = prev.getNext();
                if(current != null) {
                    prev.setNext(current.getNext());
                } // end if
            } // end else
            count--;
        } // end if
        else {
            // position = count
            ...
        } // end else
    } // end remove()
Avatar of luna621

ASKER

Oh wait.  Nevermind.   >_<''
Avatar of luna621

ASKER

   public void remove(int position) throws SortedListException {
        ...
                DLN prev = (DLN)get(position);
        ...
    } // end remove()

    public Comparable get(int position) throws SortedListException {
        ...
    } // end get()

If I'm sending size(), which is count, an integer... I get a null pointer.  If I'm sending size()-1, I get a ClassCastException.  Why is that?
Avatar of luna621

ASKER

   public Comparable get(int position) throws SortedListException {
        DLN current = head;
        for (int skip = 0; skip < position; skip++) {
            current = current.getNext();
        } // end for
        return current.getItem();
    } // end get()

Should I add an 'if' statement somewhere in there

if(position is the last node) {
   do something;
} // end if
Hey luna,

I'm back in.
Forgive me if I say, but I find it a pitty you don't read the comments in more detail.

(1) Why do you still use the get() function that returns a Comparable if you have such a nice find() function that returns nicely a DLN

Why writing:

         DLN prev = (DLN)get(position);
or
         DLN nodeToDelete = get(position);

if you can write

         DLN prev = find(position);
or
         DLN nodeToDelete = find(position);

Please use find()!!!

(2) Why do you keep writing such an extended remove(int position) function if it can be written
as
public void remove(int position) throws SortedListException {
        if (position >= 0 && position <= count) {
            DLN nodeToDelete = find(position);
            remove(nodeToDelete);
        } // end if
        else {
            System.out.println("List index out of bounds exception on remove");
        } // end else
} // end remove()

The same code as your previous removePos() function. You may remove functions, but keep the way they were working.

>>  the removeAll() seems to work ok...
I didn't say it wasn't, but it had memory leaks

Avatar of luna621

ASKER

Basically, I need to use:

    public Comparable get(int position) throws SortedListException {

-not-

    public DLN find(int index) {

Though I wish I could, since it's easier  :)

And I need to use:

    public void remove(Comparable item) throws SortedListException {

-not-

    public DLN remove(DLN nodeToRemove) {


Arrrgghh!!   >_<''
Avatar of luna621

ASKER

>(2) Why do you keep writing such an extended remove(int position) function if it can be written

I think I changed it because the get() wasn't working in there.  Once I have the get() working properly, I'll change it back  :)
Avatar of luna621

ASKER

   public Comparable get(int position) throws SortedListException {
        DLN current = head;
            for (int skip = 0; skip < position; skip++) {
                current = current.getNext(); //<---------------- do I need to check if getNext() = null?
            } // end for
            return current.getItem();
    } // end get()
>> Why do you still use the get() function that returns a Comparable if you have such a nice find() function

Correct. You don't need both. Use only one of them.

>> If I'm sending size(), which is count, an integer... I get a null pointer.  If I'm sending size()-1, I get a ClassCastException.  Why is that?

Because when you send size (), you go one ahead of the last node. So before it can cast, it throws a NullPointer. When you send size () - 1, you reach the correct node (so there is no NullPointer), but there is a casting-problem.
>> current = current.getNext(); //<---------------- do I need to check if getNext() = null?

That would arise if you pass a value for position which is >= size (). To be on the safe side, you can check. But I guess that you will not be passing such a value anywhere in your program.
Avatar of luna621

ASKER

>Because when you send size (), you go one ahead of the last node. So before it can cast, it throws a NullPointer. When
>you send size () - 1, you reach the correct node (so there is no NullPointer), but there is a casting-problem.

Is there a way to correct this?
>> Is there a way to correct this?

If you handle with a check -> whether getNext () returns null or not, then the NullPointer can be handled.

For the class-cast, well - the correct object has to be passed.
Well, if you can't use find() then make get() work as find() ;)

   public Comparable get(int position) throws SortedListException {
        DLN current = head;
        for (int skip = 0; skip < position; skip++) {
            current = current.getNext();
        } // end for
        return current;  // instead of current.getItem()
    } // end get()

I don't understand why you return

           current.getItem();

In your SortedList class you're dealing with DLN objects. Forget about what's in it.
Work with DLN objects. And since you made your DLN class implementing the Comparable interface it's OK for the return type.

Of course, don't forget to check all your code for this new return object.
>> Forget about what's in it.
I mean in the DLN objects
I still see:

DLN nodeTmp = new DLN(get(count/2));

Make that (with your new get()):

DLN nodeTmp = get(count/2);

>> return current;  // instead of current.getItem()

I think that should correct the ClassCast. Perhaps that is why it was throwing it. And I never noticed that this method should return a DLN !
Also in your add()

DLN nodeTmp = head;         ====>   DLN nodeTmp = get(count/2);

You see, how easy things become?

By the way:

>>And I need to use:
>>
>>    public void remove(Comparable item) throws SortedListException {
>>
>>-not-
>>
>>    public DLN remove(DLN nodeToRemove) {

You need to use remove(Comparable item).
That's OK. [ Remember item being a DLN object, not a Person object what's in it. If you have a Person object P and want to call remove(P), well then call remove(new DLN(P)); ]

But *how* you implement that remove(Comparable item) is your business. No?
Well, who forbids you to have remove(Comparable  item) call your own remove(DLN node) function that nicely takes care of (1), (2) & (3)? Nobody!
Just do it.


Avatar of luna621

ASKER

Okaaaaay!!!  Re-introduced the find(), and everything is working nicely.  Now I need to test a bit more...

>> I think that should correct the ClassCast. Perhaps that is why it was throwing it.
Sure. Saw it already, but always forget to mention. There's so much comments here... ;)

So: read my first comments again containing the removeXXX() codes.
      and replace find() by get()

>> Okaaaaay!!!  Re-introduced the find(), and everything is working nicely
But you say you have to use get()???
Anyway, whatever you use, find() or get() or yodelahey() *make sure it returns a DLN object*!!!
>> Re-introduced the find(), and everything is working nicely

Perhaps the modified get () looked better.
>> everything is working nicely
Don't forget my comments about the memory leaks!
That's something you don't *see*, even if all is working nicely.
Avatar of luna621

ASKER

Forgive me!!  I'm confusing everyone including myself  ^_^''

Okay, one last question (I hope).

I'm trying to make sure duplicate IDs are not added.  I know the add() checks that already, but I also want my applet to display the error msg: "Duplicate ID.  Could not be added."  I was thinking of making a checkDup():

    public int checkDup(Comparable person,int iIDInput) {
        DLN node = new DLN(person);
        DLN nodeTmp = head;
        // need to traverse list and compare to each node???
        int newID = node.compareTo(person);
            if(newID == iIDInput) {
                return 0;
            } // end if
        return -1;
    } // end checkDup()

Then call it in my applet as:
                               ...
                                Person person = new Person(nameInput,iIDInput);
                                    if(list.checkDup(person, iIDInput)!=0) {
                                        list.add(person);
                                        listArea.setText("");
                                        list.printList(listArea);
                                    } // end if
                                    else {
                                        error.setText("Duplicate ID.  Can't add to list.");
                                    } // end else
                                 ...
I have already told you about that - use the JOptionPane.showMessageDialog ().
>> error.setText("Duplicate ID.  Can't add to list.");

Use the JOptionPane there.
Avatar of luna621

ASKER

>Pass the Applet as the <parent-frame>. You will need to pass it as an extra parameter somehow to SortedList.java.

How do I pass the applet?  Do I pass the name of the applet?
Why even not use JOptionPane.showMessageDialog() in your add() function

instead of

System.out.println("\nSorry! A Person with this ID already exists!\n");

>> I know the add() checks that already, but I also want my applet to display the error msg: "Duplicate ID.  Could not be added."
Well,

           JOptionPane.showMessageDialog()

in your add() function should work
It's *never* a good idea to have the same logic (checking for double IDs) in two or more functions (add() & checkDup())

Because, when you change one, you always have to change the other functions too.
And then you forget one and you can go bug hunting.
>> How do I pass the applet?  Do I pass the name of the applet?

If you're calling it in your applet, pass this.
>> System.out.println("\nSorry! A Person with this ID already exists!\n");

It might be better to remove all System.out.println () statements now that you are working with Applets. But display the error message only once - not in the checkDup () or add () method as well as the Applet (it would be better to display in the applet, because then you can pass 'this', otherwise, you need to pass it somehow as an extra parameter to checkDup () or add () for displaying).
Avatar of luna621

ASKER

           ...
            else if (cmpResult==0) {
                System.out.println("\nSorry! A Person with this ID already exists!\n");
                JOptionPane.showMessageDialog(); // show a warning message
                break;
            } // end if
            ...

Do I need to import or extend something, because I get this error:

symbol  : variable JOptionPane
location: class SortedList
                JOptionPane.showMessageDialog(); // show a warning message
                ^
1 error
Avatar of luna621

ASKER

Oh, I should write that in the applet class??
impot javax.swing.JOptionPane ;
>> Oh, I should write that in the applet class??

Yes, write it in the applet - the place where you do. error.setText ( "...." ) ;

JOptionPane.showMessageDialog ( this, "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE ) ;
Avatar of luna621

ASKER

symbol  : method showMessageDialog (OrderedList.Ears,java.lang.String,java.lang.String,int)
location: class javax.swing.JOptionPane
                                error.setText(JOptionPane.showMessageDialog(this, "Sorry! A Person with this ID already exists!  
                                                                                         Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE));
                                                                       ^
1 error

This is what I put:

error.setText(JOptionPane.showMessageDialog(this, "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE));
Avatar of luna621

ASKER

Do I need to write a new method in the applet class that passes (String, String, int)??
>> Oh, I should write that in the applet class??
Indeed, that's mayankeagle's (good) proposal.
Because showMessageDialog() needs some parameters that are not available in your SortedList class but in your applet.

So that's why we propose:

1) don't introduce a checkDup()
2) don't System.out.println(...) in add() but throw an exception instead
    [ This way you'll really "use" the "throws SortedListException" part of add() ]
3) catch that exception in your applet and if it occurs perform a showMessageDialog() with the right message
Hey,

NOT

error.setText(JOptionPane.showMessageDialog(this, "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE));

but

JOptionPane.showMessageDialog(this, "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE);

Remove error.setText ();
See the 3rd comment that I posted on this page at the start.
Avatar of luna621

ASKER

Ok, I removed it but it still gives me:

symbol  : method showMessageDialog (OrderedList.Ears,java.lang.String,java.lang.String,int)
location: class javax.swing.JOptionPane
                                error.setText(JOptionPane.showMessageDialog(this, "Sorry! A Person with this ID already exists!  
                                                                                         Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE));
                                                                       ^
1 error
Avatar of luna621

ASKER

Sorry, once more:

symbol  : method showMessageDialog (OrderedList.Ears,java.lang.String,java.lang.String,int)
location: class javax.swing.JOptionPane
                                JOptionPane.showMessageDialog(this, "Sorry! A Person with this ID already exists! Oro! :-                                                                                ) ", "ALERT", JOptionPane.WARNING_MESSAGE);
                                                    ^
1 error
>> this

Oh, its referring to the inner-class.
Where do you instantiate the Ears class? Pass the Applet to it as an argument and store it in a member of the Ears class. Then use that member instead of 'this'.
Avatar of luna621

ASKER

Ok, instead of 'this', what should I put?

>See the 3rd comment that I posted on this page at the start.

I pasted that in the add(), and it gave:

1.  illegal start of expression
                JOptionPane.showMessageDialog ( <parent-frame>, "Sorry! A Person with this ID already exists! Oro! :-
                                                                                            ) ", "ALERT", JOptionPane.WARNING_MESSAGE ) ; // show
                                                                                            a warning message
                                                                       ^
2.  ')' expected
                JOptionPane.showMessageDialog ( <parent-frame>, "Sorry! A Person with this ID already exists! Oro! :-
                                                                 ) ", "ALERT", JOptionPane.WARNING_MESSAGE ) ; // show a warning message
                                                                                                                                       ^
2 errors
I think we better stop posting with the speed of light... ;)
luna, I'm gonna let this last part to mayankeagle.
Our concurrent posts confuse you. And that's not the goal.

See you at the accept.
bye
Avatar of luna621

ASKER

Okay, Ears is located in OrderedList.java (my applet class):

    public class Ears implements ActionListener {
        ...
    } // end Ears

>Pass the Applet to it as an argument and store it in a member of the Ears class.

Do you mean:

    public class Ears(Applet applet) implements ActionListener {
        ...
    } // end Ears
Actually, you can give a try to:

JOptionPane.showMessageDialog ( e.getSource ().getParent (), "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE);

e.getSource () would be the button and .getParent () of that will give you the Applet :-)
Avatar of luna621

ASKER

Bye zzynx!  Thank you for your help!!  =^^=

See you soon!!  :)
Or perhaps: e.getSource ().getParent ().getParent ()

Just noticed that the button is in a Panel, so that would be its parent, and the parent of the Panel would be the Applet.

>> public class Ears(Applet applet) implements ActionListener

No. The constructor should be like:

public class Ears implements ActionListener
{
  private Applet applet ;

  public Ears ( Applet applet )
  {
    this.applet = applet ;
  }

  public void actionPerformed ( .... )
  {
    ..
    JOptionPane.showMessageDialog ( applet, "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE);

  }

}
Avatar of luna621

ASKER

1.  cannot resolve symbol
symbol  : method showMessageDialog (OrderedList.Ears,java.lang.String,java.lang.String,int)
location: class javax.swing.JOptionPane
                                JOptionPane.showMessageDialog(this, "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE);
                                           ^
2.  cannot resolve symbol
symbol  : variable e
location: class SortedList
                JOptionPane.showMessageDialog(e.getSource().getParent(), "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE ) ; // show a warning message
                                              ^
2 errors

This is what I have in the add():

            else if (cmpResult==0) {
                JOptionPane.showMessageDialog(e.getSource().getParent(), "Sorry! A Person with this ID already exists! Oro! :-
                ) ", "ALERT", JOptionPane.WARNING_MESSAGE ) ; // show a warning message
                break;
            } // end if

And this is in the Ears class:

              JOptionPane.showMessageDialog(this, "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT",
                     JOptionPane.WARNING_MESSAGE);
Don't put it in add (). Put:

>> JOptionPane.showMessageDialog(e.getSource().getParent(), "Sorry! A Person with this ID already exists! Oro! :-
                ) ", "ALERT", JOptionPane.WARNING_MESSAGE ) ;

in Ears.
Like I already said, you don't need to put it in 2 locations. Putting it in the Applet itself is enough (I mean - putting it in the actionPerformed () method of Ears).
Avatar of luna621

ASKER

Oops!!  Sorry!!  Let me try that!
Avatar of luna621

ASKER

1.  cannot resolve symbol
symbol  : method getParent ()
location: class java.lang.Object
                                JOptionPane.showMessageDialog(e.getSource().getParent(), "Sorry! A Person with this ID already exists! Oro!", "ALERT", JOptionPane.WARNING_MESSAGE ) ;
                                                                         ^
2.  cannot resolve symbol
symbol  : variable e
location: class SortedList
                JOptionPane.showMessageDialog(e.getSource().getParent(), "Sorry! A Person with this ID already exists! Oro! :-) ", "ALERT", JOptionPane.WARNING_MESSAGE ) ; // show a warning message
                                              ^
2 errors
-------------------------------------------------------------
I thought I defined the variable 'e' as:    public void actionPerformed(ActionEvent e)
Avatar of luna621

ASKER

Or do I need to assign 'e' to a value like how I did with:  String whichButton = e.getActionCommand();
( ( Button ) e.getSource () ).getParent ().getParent ()
e.getSource () returns an Object, so you need to type-cast it to Button so that you can use the getParent () method.

>> location: class SortedList

You STILL have it in the SortedList class. Remove it from there. Like I said - put it ONLY in the Ears class.
>> Or do I need to assign 'e' to a value like how I did with:  String whichButton = e.getActionCommand();

No. That's not needed. You don't need thae JOptionPane in the SortedList class. The JVM will generate the event and send it to the actionPerformed () method of the Ears class.
Avatar of luna621

ASKER

try {
                                Person person = new Person(nameInput,iIDInput);
                                list.add(person);
                                listArea.setText("");
                                list.printList(listArea);
                                JOptionPane.showMessageDialog(((Button)e.getSource()).getParent().getParent(), "Sorry! A Person with this ID already exists! Oro!", "ALERT", JOptionPane.WARNING_MESSAGE ) ;
                             } // end try
                            catch (SortedListException ex) {

Ok, right now I have it in the try, so it pops up everytime I add a person.  If I wanted it to pop up only if the IDs are equal, where do I put it?  I tried moving it to the catch area, but nothing pops up.
Avatar of luna621

ASKER

>You STILL have it in the SortedList class. Remove it from there. Like I said - put it ONLY in the Ears class.

Must have forgotten about that one.  Sorry!!!  ^_^''
Avatar of luna621

ASKER

Do I need to put something here:

            else if (cmpResult==0) {
                break;

in the add() to tell it to pop a message?
>> in the add() to tell it to pop a message?

No. That's the whole idea. You're not supposed to pop up a message there. You have to pop up a message in the Applet. That's why I said - put it onl in Ears. Let this:

>> else if (cmpResult==0) {
>> break;

- stay as it is.

>> If I wanted it to pop up only if the IDs are equal, where do I put it?

Do you not have the checkDup () method anymore? If you have it, then wherever you call it from the Applet, if it returns a 0 - then you should pop up the message.

>> I tried moving it to the catch area, but nothing pops up

That is wrong logic. Control will go to the catch only if there is an exception and if there is an exception, then you don't need to display 'that' message :-)
Avatar of luna621

ASKER

Ok, I added this:

    public boolean popUp() {
        if(popUp==true) {
            return true;
        }
        return false;
    } // end popUp()
----------------------------------------------------------------------------
And this from the add():

            ...
            else if (cmpResult==0) {
                popUp = true;
                break;
           ...
----------------------------------------------------------------------------
And this from the applet class:

                           try {
                                Person person = new Person(nameInput,iIDInput);
                                if(list.popUp()==true) {
                                    JOptionPane.showMessageDialog(((Button)e.getSource()).getParent().getParent(), "Sorry! A
                                    Person with this ID already exists! Oro!", "ALERT", JOptionPane.WARNING_MESSAGE ) ;
                                } // end if
                                if(list.popUp()==false) {
                                    list.add(person);
                                    listArea.setText("");
                                    list.printList(listArea);
                                } // end if
                             } // end try

Avatar of luna621

ASKER

Only thing is, I have click the "Add" button on the same ID twice before the pop-up pops up.
Avatar of luna621

ASKER

Also, once the message appears... it'll keep appearing even if I add a different ID number.
ASKER CERTIFIED SOLUTION
Avatar of Mayank S
Mayank S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> Make popUp = false in all if-else cases, other than: >> else if (cmpResult==0) {

Only in that method.
Avatar of luna621

ASKER

HAHAHAHahahaha.... stupid me!  I forgot to add the person to the list first.  Okay, it works now.  Thank you (x3)!!

Woo!!  12:30 am!!  Better get some shut eye.  

I have learned many new things today.  Thank you again!

-luna621 =^^=
Did you accept only my answer? I guess zzynx also helped you enough. You should give him some points in another question "Points for zzynx" and post a link to that question on this one so that he can go there and collect them.

Good night ;-)
mayankeagle, thanks for your honesty.
I'm indeed rather disappointed luna didn't split up the points.
:(
Welcome ;-)

>> I'm indeed rather disappointed luna didn't split up the points

I guess it was just in a hurry because (s)he wanted to go to catch some shut eye. But as far as I have seen, (s)he is one of the most honest questioners and active questioners, so I guess by tomorrow, you should get your points in another Q :-)
>> But as far as I have seen, (s)he is one of the most honest questioners and active questioners
I agree with that.

>> so I guess by tomorrow, you should get your points in another Q
That's what I think/expect too.
Avatar of luna621

ASKER

Sorry, I haven't been checking this lately.  Yup, you got me good.  I was sleepy and I guess I forgot to split points... you know I usually do :)

zzynx, check the posting place again :)

-luna621 =^^=
Thanks luna!
CU