gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:33:37 26 4
gpt4 key购买 nike

我正在研究来自 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com