Skip to content
Advertisement

Is there a way to deal with ‘java: bad operand types for binary operator ‘!=” in this piece of code?

I have this code and it is coming up with the following error:

java: bad operand types for binary operator ‘!=’ first type: Node
second type: int

It is suppose to have the head be 3 and the next Node have data 4. Then the while loop is suppose to print each data from each Node.

class Node {
    Node next = null;
    int data;

    public Node(int d) {
        data = d;
    }


    Node appendToTail(int d) {
        Node end = new Node(d);
        Node n = this;
        while (n.next != null) {
            n = n.next;
        }
        n.next = end;
        return end;
    }

    public static void main(String[] args) {
        Node t;
        Node obj = new Node(3);
        t = obj.appendToTail(4);
        while (t != 0)
        {
            System.out.println(t);
            

        }
    }
}

////

Expected output:

3 4

Advertisement

Answer

Your current code, even if fixed, would result in an infinite loop, because once the while loop is entered, its condition does not change.

I think you want:

while (t != null)

but that doesn’t solve the infinite loop problem.

To have code that behaves as you expect:

for (t = obj; t != null; t = t.next) {
    System.out.println(t.data);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement