2014-10-03 28 views
0

我正在研究來自加州大學伯克利分校的this視頻的鏈接列表。然而,當我嘗試在我的Eclipse編譯器輸入相同的版本,像這樣的....Java - 變量聲明ID預期在此令牌之後,將值分配給實例變量時

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

任何人都可以解釋我要去哪裏錯了嗎?

回答

1

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

    } 
} 
0

不應該;噸這些線是在main()函數:

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

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

你在問或說明嗎? – 2014-10-03 02:55:30

+0

陳述@SotiriosDelimanolis :) – Satya 2014-10-03 02:56:45

1

此代碼

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文件。

+1

歡呼編輯 – 2014-10-03 02:58:32

1

你不能初始化這樣

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

你必須把它移到一些的class CreateLinkedList 方法如果你把它放在主必須聲明節點實例static

static Node first; 
static Node second; 
static Node third; 
+0

好吧,那有效。但是,爲什麼他們必須在方法中初始化?另外,視頻中的教授爲什麼不這樣做? – satnam 2014-10-03 03:45:27