Java - 将值分配给实例变量时,应在此标记之后使用 VariableDeclaratorID

标签 java class variables object

我正在研究来自 this 的链表来自加州大学伯克利分校的视频。然而,当我尝试在我的 Eclipse 编译器中输入相同的版本时,就像这样......

public class CreateLinkedList{

    public class Node{
        String PlayerName;
        Node next;
    }


    Node first = new Node();
    Node second = new Node();
    Node third = new Node();

    first.PlayerName = "Sanchez";
    second.PlayerName = "Ozil";
    third.PlayerName = "Welbeck";


    public static void main(String[] args) {

    }
}

我在以下行中收到错误“ token “PlayerName”的语法错误,此 token 后应为 VariableDeclaratorID”

first.PlayerName = "Sanchez";
second.PlayerName = "Ozil";
third.PlayerName = "Welbeck";

谁能解释我哪里出错了?

最佳答案

评论 nested class definitions ...如果您想从静态上下文中设置属性...您需要一个静态类。

public class CreateLinkedList{

static class Node{
    String playerName;
    Node next;
}

public static void main(String[] args) {

    Node first = new Node();
    Node second = new Node();
    Node third = new Node();

    first.playerName = "Sanchez";
    second.playerName = "Ozil";
    third.playerName = "Welbeck";

    System.out.println("First is : " + first.playerName);
    System.out.println("Second is : " + second.playerName);
    System.out.println("Third is : " + third.playerName);

    }
}

如果您希望将您的内部类保留为嵌套的公共(public)类,那么您需要先实例化上层类。

public class CreateLinkedList {

    public class Node {
        String playerName;
        Node next;
    }

    public static void main( String[] args ) {

        Node first = new CreateLinkedList().new Node();
        Node second = new CreateLinkedList().new Node();
        Node third = new CreateLinkedList().new Node();

        first.playerName = "Sanchez";
        second.playerName = "Ozil";
        third.playerName = "Welbeck";

        System.out.println( "First is : " + first.playerName );
        System.out.println( "Second is : " + second.playerName );
        System.out.println( "Third is : " + third.playerName );

    }
}

关于Java - 将值分配给实例变量时,应在此标记之后使用 VariableDeclaratorID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26172632/

相关文章:

java - java/c++ 中的 WLAN SSID

java - 如何正确地对 EJB3 和 servlet 进行分层?

c++ - 在 C++ 中定义对象而不调用其构造函数

c++ - 包含类文件后的错误消息(多个定义的符号)

c++ - 运算符重载使用operator +作为类模板

php - 查询结果存入变量

java - bean 验证获取验证组

java - 使用 Jackson 反序列化期间对列表属性中的对象列表进行分组

c++ - 紧接着声明的变量地址是否在彼此之前?

c++ - 如何使用用户输入的变量来定义另一个变量