g24 g24 - 28 days ago 7
Java Question

Java nodes and making a method work

I've literally lost my mind trying to figure out why my

add()
and
print()
methods won't work. I've tried virtually everything but I just can't do this. I know my code is dead wrong (I can't even tell if my code was right at one point or another because I deleted it to try new things) so what could be wrong with it?

I appreciate you taking the time to read.

NodeFN class:

public class NodeFN {
private String data; // Data for node.
private NodeFN next; // Next node.

public NodeFN(String data) {
this.data = data; // Take the data value passed in & store it in the data field.
this.next = null; // Take the next node & store it in the next field.
}

// Mutator functions.
public String getData() {return data;}
public NodeFN getNext() {return next;}
public void setData(String d) {data = d;}
public void setNext(NodeFN n) {next = n;}
}


Queue class:

public class Queue {
NodeFN head; // Head of node.
public String n;

public Queue(String n) {
head = new NodeFN(n); // head is now an object of NodeFN which holds a string.
}

public void add(String n) {
NodeFN nn = new NodeFN(n); // nn is now an object of NodeFN which holds a string, it should return something.
if(head == null) {
head = nn;
}
while(nn.getData().compareTo(head.getData()) < 0) {
nn.setNext(head); // Put node in beginning of the list.
nn.setData(n);
}
}

public void print() {
NodeFN nn = new NodeFN(n);

while(nn != null) {
nn.getNext().getData();
System.out.println(nn.getData() + " ");
}
}

public static void main(String[] args) {
Queue q = new Queue("string to test");
q.add("another string to test if add method works.");
q.print();
}
}

Answer

I can't speak for your add method, but what is n here ?

public void print() {
    NodeFN nn = new NodeFN(n);

    while(nn != null) {
        nn.getNext().getData();
        System.out.println(nn.getData() + " ");
    }
}

The queue class should not care about public String n at all. You only need the head Node.

Then, nn.getNext().getData(); is returning something, yes? But, you are not printing it nor are you "moving forward" in the list. (You don't assign nn to the next node).

Try something like this

public void print() {
    if (head == null) System.out.println();

    NodeFN tmp = head;

    while(tmp != null) {
        System.out.println(tmp.getData() + " ");
        tmp = tmp.getNext();
    }
}

If you want the nodes to be add at the start of the list, then this should work.

public void add(String n) {
    NodeFN nn = new NodeFN(n);
    if(head == null) {
        head = nn;
    }

    // Don't use a while loop, there is nothing to repeat
    if (nn.getData().compareTo(head.getData()) < 0) {
        // Both these operations put 'nn' in beginning of the list.
        nn.setNext(head); 
        head = nn;
    }
}
Comments