【问题标题】:Why won't my code recognize this method of my Node object?为什么我的代码不能识别我的 Node 对象的这个方法?
【发布时间】:2020-08-11 18:37:06
【问题描述】:

我有这个节点类,它有一个实例变量,它是一个数组列表,它将保存它的所有邻居。

我有设置和获取实例变量的方法,包括我的 arraylist 实例变量“neighborhood”。

当调用方法`addNeighbor()~,我的代码给了我一个错误。它对我大喊大叫的都是语法错误,但我不确定我的代码有什么问题。

import java.util.ArrayList;

public class Node {

    static Node parent;
    static char key;
    static int time;
    static ArrayList<Node> neighborhood = new ArrayList();

    public Node(char Key) {
        parent = null;
        key = key;
        time = -1;
    }

    public static void setTime (int x) {
        time = x;
    }

    public static void setKey (char x) {
        key = x;
    }

    public static void setParent (Node x) {
        parent = x;
    }

    public static void addNeighbor (Node x) {
        neighborhood.add(x);
    }

    public static int getTime (){
        return time;
    }

    public static char getKey() {
        return key;
    }

    public static Node getParent() {
        return parent;
    }

    public static ArrayList<Node> getNeighborhood(){
        return neighborhood;
    }
}

课堂实验7

public class lab7 {

    Node A = new Node('A');
    Node B = new Node('B');
    Node C = new Node('C');
    Node D = new Node('D');
    Node E = new Node('E');
    Node F = new Node('F');
    Node G = new Node('G');

    int time = A.getTime();

    A.addNeighbor(B);  // error occurs HERE


    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

【问题讨论】:

    标签: class arraylist methods syntax-error nodes


    【解决方案1】:

    addNeighbor 方法返回 void,您不能使用外部方法。

     public class lab7 {
            public static void main(String[] args) {
            Node A = new Node('A');
            Node B = new Node('B');
            Node C = new Node('C');
            Node D = new Node('D');
            Node E = new Node('E');
            Node F = new Node('F');
            Node G = new Node('G');
    
            int time = A.getTime();
            A.addNeighbor(B);
    
        }
    }
    

    【讨论】:

    • 谢谢。我意识到它只有在我主要调用它时才有效。
    • @LoFitz546 它必须在方法中调用
    • @LoFitz 546 感谢您接受回答!如果您不介意,可以 +1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 2019-07-02
    • 2015-01-21
    • 2014-02-06
    • 2014-02-04
    • 1970-01-01
    相关资源
    最近更新 更多