繁体   English   中英

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

[英]Java - VariableDeclaratorID expected after this token, when assigning value to an instance variable

我正在研究UC Berkeley 这段视频中的链接列表。 但是,当我尝试在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) {

    }
}

我在以下行上收到错误“令牌“ PlayerName”上的语法错误,此令牌后需要VariableDeclaratorID”

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

谁能解释我要去哪里错了?

这段代码

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

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

不在代码块中,请尝试将其移至main

此外, Node类将需要static ,否则将其移动到单独的.java文件中。

你不能这样初始化

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

您必须将其移至class CreateLinkedList某些方法中如果将其放在main中,则必须声明Node实例为static

static Node first;
static Node second;
static Node third;

查看嵌套的类定义 ...如果要从静态上下文设置属性,则需要一个静态类。

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 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 );

    }
}

这些行不应该在main()函数中:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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