[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 236
  • Last Modified:

Debugging error on linked list

Hello all,
   I've written this program and it compiles perfectly, but when I run the program and I type "print" into the command window nothing happens. Can someone please take a look at my code and see what logic I've done wrong. I'm at wits end with this. Any help I can get would be truly appreciated!!


Thank you and I'm looking forward to your reply!
/**HERE IS THE FIRST CLASS**/
 
 
public class Node
{
    private String firstName;
    private String phone;
    private int age;
    private Node rp;
 
 
    /**
     * <pre>
     * Description: 
     * Construct the strings and integer variables.
     * Pre:
     * None.
     * Post:
     * We have an object of class Node.
     * </pre>
     * 
     */   
    public Node()
    {
        firstName = "";
        phone = "";
        age = 0;
        rp = null;
    }
 
    /**
     * <pre>
     * Description: 
     * Construct string and integer variables with specified firstName, phone, and age.
     * Pre:
     * None.
     * Post:
     * Have an objects of class Person that has specified values.
     * </pre>
     */
    public Node(String firstNameX, String phoneX, int ageX)
    {
        firstName = firstNameX;
        phone = phoneX;
        age = ageX;
      
    }
    
    /**
     * <pre>
     * Description: 
     * Set firstName.
     * Pre:
     * None.
     * Post:
     * Have format firstNameX with specified firstName.
     * </pre>
     */
    public void setFirstName(String firstNameX)
    {
        firstName = firstNameX;
    }
   
    /**
     * <pre>
     * Description: 
     * Return firstName.
     * Pre:
     * none
     * Post:
     * Return firstName.
     * </pre>
     */
    public String getFirstName()
    {
        return (firstName);
    }
 
    /**
     * <pre>
     * Description: 
     * Set phone.
     * Pre:
     * None.
     * Post:
     * Have format phoneX with specified phone.
     * </pre>
     */
    public void setPhone(String phoneX)
    {
        phone = phoneX;
    }
 
    /**
     * <pre>
     * Description: 
     * Return phone.
     * Pre:
     * none
     * Post:
     * Return phone.
     * </pre>
     */
    public String getPhone()
    {
        return (phone);
    }
 
    /**
     * <pre>
     * Description: 
     * Set age.
     * Pre:
     * None.
     * Post:
     * Have format ageX with specified yearBorn.
     * </pre>
     */
    public void setAge(int ageX)
    {
        age = ageX;
    }
 
    /**
     * <pre>
     * Description: 
     * Return age.
     * Pre:
     * none
     * Post:
     * Return age.
     * </pre>
     */
    public int getAge()
    {
        return (age);
    }
 
    public void setRp(Node newRp)
    {
        rp = newRp;
    }
 
    public Node getRp()
    {
        return (rp);
    }
 
	/**
	 * <pre>
	 * Description: 
	 * prints the name, phone number, and age.
	 * Pre:
	 * None.
	 * Post:
	 * Line with specified information will be printed.
	 * </pre>
	 *
	 */
    public void print()
    {
       System.out.println("name=" + firstName + "\t" + "phone=" + phone + "\t" + "age=" + age);
    }
}
 
 
 
/**HERE IS THE SECOND CLASS**/
import java.io.*;
import java.util.*; /** Scanner **/
import java.util.regex.*; /** Pattern **/
public class AddressList
{
    private Node head;
    private Node nrp;
    private Node ptr1;
    private Node ptr2;
 
    /**
     * <pre>
     * Description: 
     * Construct the Node's references
     * Pre:
     * None.
     * Post:
     * We have an object of class AddressList.
     * </pre>
     * 
     */   
    public AddressList()
    {
        head = null;
        nrp = head;
        ptr1 = null;
        ptr2 = null;
 
    }
 
    /**
     * <pre>
     * Description: 
     * Add a person to the linked list
     * Pre:
     * New node.
     * Post:
     * The newPerson Node will have a new person added to it.
     * </pre>
     */
    public void addAddressIter(Node newPerson)
    {
        Node nxp = newPerson;
        if(nrp == null)
        {
            head = newPerson;
            return;
        }
 
	
        else if (nrp.getRp() != null)
        {
            nrp = nrp.getRp();
	    System.out.println(nrp);
        }
        nrp.setRp(nxp);
 
    }
 
    /**
     * <pre>
     * Description: 
     * Delete a person from the linked list.
     * Pre:
     * None.
     * Post:
     * The linked list will have a person deleted and have an open space in it.
     * </pre>
     *
     */
    public void removeAddressIter(String firstName)
    {
        if(nrp == null)
        {
            System.out.println("not found");
        }
        else
        {
            if(nrp.getRp().equals(firstName))
            {
                head = nrp.getRp();
                return;
            }
            else
            {
                ptr1 = head;
                ptr2 = ptr1.getRp();
                while(ptr2 != null)
                {
                    if(ptr2.getRp().equals(firstName))
                    {
                        ptr1.setRp(ptr2.getRp());
                        return;
                    }
                    ptr1 = ptr1.getRp();
                    ptr2 = ptr1.getRp();
                }
                System.out.print("not found");
                return;
            }    
        }
    }
 
    /**
     * <pre>
     * Description: 
     * Print the linked list's data
     * Pre:
     * None.
     * Post:
     * Print.
     * </pre>
     *
     */
    public void printIter()
    {
        if(nrp != null)
        {
            nrp.print();
            nrp = nrp.getRp();
        }
 
    }
 
    /**
     * <pre>
     * Description: 
     * Test the program by performing few operations
     * Pre:
     * none
     * Post:
     * none
     * </pre>
     * 
     */
    public static void main(String[] args)
    {
        AddressList alist = new AddressList();
        Scanner sc = new Scanner(System.in);
        String op1 = "";
        while(op1.equalsIgnoreCase(op1))
	{
            System.out.println("Do you want to do add or delete or print or quit");
	    op1 = new String(sc.next());
            
            if(op1.equals("quit"))
            {
                return;
            }
            if(op1.equals("add"))
            {
                System.out.println("please type name, yearBorn, phone");
                String inputFirstName = sc.next();
                int inputAge = sc.nextInt();
                String inputPhone = sc.next();
 
                alist.addAddressIter(new Node(inputFirstName, inputPhone, inputAge));
            }
            if(op1.equals("delete"))
            {
                System.out.println("please type name of person to be deleted");
	        String firstName = sc.next();
                alist.removeAddressIter(firstName);
            }
            if(op1.equals("print"))
            {
                alist.printIter();	
            }
        }
    }
 
 
}

Open in new window

0
ccsk89
Asked:
ccsk89
  • 6
  • 5
1 Solution
 
Kevin CrossChief Technology OfficerCommented:
Hello ccsk89,

You are not setting the nrp object to anything based on the logic since nrp starts out null, it always falls into the logic to set head = newPerson and then return when you add someone new.  Then when you printIter() you won't get anything printed as nrp == null.

Hope that makes sense.

Best regards,

mwvisa1
public void addAddressIter(Node newPerson)
    {
        Node nxp = newPerson;
        if(nrp == null)
        {
            head = newPerson;
// need to create nrp or set to newPerson here
            return;
        }
 
      
        else if (nrp.getRp() != null)
        {
            nrp = nrp.getRp();
          System.out.println(nrp);
        }
        nrp.setRp(nxp);
 
    }

Open in new window

0
 
ccsk89Author Commented:
So basically what you are saying is that i need to set nrp = newPerson.. I just tried that and it worked! Wow! Thanks! I was shown how to do the add method the way I did it and I didn't think I would have been taught wrong. But I thought that since both head and nrp were null, it would work out I guess.

I just ran the program just now..and now when I go to add the program is only letting me add two people and then I get an error. What could I possibly be doing now? (I can ask a new question if you would prefer another 500 points:) since your such a great help)
0
 
Kevin CrossChief Technology OfficerCommented:
Sorry you were mislead.  Think I answered your deletion question question...hopefully my comments there didn't steer you down this path.

If I understand correctly, you have set nrp = newPerson on first run; then second add you set rp.  Now on third and subsequent runs, you must set the rp of the rp.  Hopefully you followed that...

Not sure if my implementation is correct here, but first shot at it as an example.

Think you need to do something like this:
public void addAddressIter(Node newPerson) {
        if (nrp == null) {
            // set head node for reference
            head = newPerson;
            // set node
            nrp = newPerson;
        } else if (nrp.getRp() != null) {
            // if right position already filled, then create temp Node
            Node nxp = nrp.getRp();
            
            // keep checking right Node of nxp until find empty rp
            while (nxp.getRp() != null) {
                nxp = nxp.getRp();
            }
            
            // set node
            nxp.setRp(newPerson);
        } else {
            // set right Node if currently null
            nrp.setRp(newPerson);
        }
    }

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
ccsk89Author Commented:
Oh no it was not you, it was a professor. You've been nothing but help:)

The adding problem is now fixed! Thank you soo much. When I type print in the command window, it still only prints one person in the list. is it because I am setting nxp and not nrp int he print method?
0
 
Kevin CrossChief Technology OfficerCommented:
Alright, think we may have accidentally made this an if statement in troubleshooting.

You need to loop in the print code and you are right, you will also want to set nxp instead of nrp as you don't want to overwrite data here you just want to retrieve the nodes to print out.

Change this code:
public void printIter()
    {
        if(nrp != null)
        {
            nrp.print();
            nrp = nrp.getRp();
        }
 
    }

To something like in the code snippet:
public void printIter() {
        Node nxp = nrp;
        
        while (nxp != null) {
            nxp.print();
            nxp = nxp.getRp();
        }
    }

Open in new window

0
 
Kevin CrossChief Technology OfficerCommented:
public void printIter() {
        Node nxp = nrp; // set a temp Node to nrp
       
        while (nxp != null) { // only do this if not null to avoid NullPointerException
            nxp.print(); // print current Node value
            nxp = nxp.getRp(); // get right Node and continue looping until right is null...
        }
    }
0
 
ccsk89Author Commented:
ok that works now! Now if I can ask you for help one more time. In my removeAddressIter method I typed delete in the command window and it deleted the wrong person that I told it to delete. But it did delete which it wasn't doing. So do you have any idea what could be getting mixed up I told the program to delete the 3rd person I added and it deleted the second instead.
0
 
ccsk89Author Commented:
The code didn't attach so here it is:)

    public void removeAddressIter(String firstName)
    {
        if(nrp.getRp() == null)
        {
            System.out.println("not found");
        }
        else
        {
            if(nrp.getRp().getFirstName().equalsIgnoreCase(firstName))
            {
                head = nrp.getRp();
                return;
            }
            else
            {
                ptr1 = head;
                ptr2 = ptr1.getRp();
                while(ptr2 != null)
                {
                    if(ptr2.getRp().getFirstName().equalsIgnoreCase(firstName))
                    {
                        ptr1.setRp(ptr2.getRp());
                        return;
                    }
                    ptr1 = ptr1.getRp();
                    ptr2 = ptr1.getRp();
                }
                System.out.print("not found");
                return;
            }    
        }
    }
0
 
Kevin CrossChief Technology OfficerCommented:
Thoughts below!
public void removeAddressIter(String firstName)
    {
// what about nrp itself
// checking if nrp.getRp() == null, but what if nrp == null
// if nrp != null, then person could be in nrp
        if(nrp.getRp() == null)
        {
            System.out.println("not found");
        }
        else
        {
// i would make above test if nrp == null then "not found"
// in this section, do something like this
/*
Node nxp = nrp;
boolean found = false;
 
// since checking null here, can even get rid of if statement above
while (nxp != null) {  
    if (nxp.getFirstName().equalsIgnoreCase(firstName)) {
       // do logic here to remove nxp while moving up rp down stream
       found = true;  // flag that you found node
    } else {
       nxp = nxp.getRp(); // go to next node
    }
}
 
if (!found) {
    System.out.println("not found");
}
*/
 
// not sure which parts of this you will keep below here
// the ptr1 one code looks like you are trying to do the reorder of Nodes
// will comment after you reorganize code with comments above as you want to do this logic where indicated above
            if(nrp.getRp().getFirstName().equalsIgnoreCase(firstName))
            {
                head = nrp.getRp();
                return;
            }
            else
            {
                ptr1 = head;
                ptr2 = ptr1.getRp();
                while(ptr2 != null)
                {
                    if(ptr2.getRp().getFirstName().equalsIgnoreCase(firstName))
                    {
                        ptr1.setRp(ptr2.getRp());
                        return;
                    }
                    ptr1 = ptr1.getRp();
                    ptr2 = ptr1.getRp();
                }
                System.out.print("not found");
                return;
            }    
        }
    }

Open in new window

0
 
ccsk89Author Commented:
Thank you very much for your help!  This morning I read what you said and it made sense. Thanks also for taking the time to comment each line. That really helps me learn more about what I am doing, especially since my teacher has been making this crazy errors which I am beginning to think he's doing it on purpose to get us to figure out what is wrong and try to fix it. But anyways, I thank you soo soo much!!! You are a big help, a genius, and are very patient! I can't thank you enough!:)

0
 
Kevin CrossChief Technology OfficerCommented:
I was hoping that helped.

Happy coding!

Best regards,
Kevin

P.S. your guess is probably correct.  Prof probably trying to make you think through the process.  I find it helpful to put comments like that in the code stub before I am even done when I was learning Java -- comment for different reasons now -- but effect is the same as it makes it clear what you are trying to do to yourself which after some time of troubleshooting something can get lost.  Trust me, I know!! :) It will be worth it though if your heart is in coding...
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now