简体   繁体   中英

next cannot be resolved to a value or field in java

I have this question:

Write a recursive java function that counts the number of nodes in a circularly linked list.

Here is the method/function:

public int countNodes(Node node){

    if (node == null) {
        return 0;
    }
    else{
            return 1+countNodes(node.next);
    }
}

I get an error in the line return 1+countNodes(node.next); which says that: next cannot be resolved to a value or field in java

What am I supposed to do to fix this error?

The way your code stands, you are trying to access a non-existent field called "next" in Node. Either add that field (if Node is a class you created), or did you mean to call a method called next? If so, do node.next()

The Node class should be like this:

public class Node {

    private Node next;

    public Node getNext(){
        return next;
    }

    //setter and other stuff


} 

and you have to call node.getNext()

 return 1+countNodes(node.getNext());

Don't forget that Java is a object oriented language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM