1

I tried searching for a similar issue, to no avail. If I change the operator from "!=" to "==", it prints "{ }". Also, if I simply print out the variable I'm testing (current.myData) the Integer that it references prints out as expected. However, every time I test "current.myData != null" it throws a null pointer exception and exits. Any help is greatly appreciated!

public class LinkedQueue<E> implements QueueADT<E> {

@Override
public String toString() {
...
    String exitVal = null;
    final StringBuffer sb = new StringBuffer();
    if (myFront.myData == null) {
        exitVal = "{ }";
    } else {
        Node<E> current = myFront.myNext;
        sb.append('{');
        sb.append(myFront.myData);
        while (current.myData != null) {
            sb.append(", ");
            sb.append(String.valueOf(current.myData));
            current = current.myNext;
        }
        sb.append('}');
        exitVal = sb.toString();
    }
    return exitVal;
}

1 Answers1

1

In the loop body, current = current.myNext; has no test for myNext being null so on either the first (or a subsequent) loop iteration current must be null. You could change

while (current.myData != null) {

to something like

while (current != null && current.myData != null) {
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • You're fix is working perfectly. Thank you! I'm not sure I fully understand it, though. Does this mean Java is checking to see that 'current' is not null before it checks if 'current.myData' is null? So, my test was hitting the actual node (or lack thereof) before the field in the node? – audiobomber May 01 '16 at 09:08