2015-06-08 127 views
-3

Java新手,請耐心等待!class - 變量聲明屬性

我能知道這是爲什麼嗎?
在聲明map hashmap時沒有錯誤,但是當我嘗試用一​​些對填充它們時出現錯誤。
如果我將它們填充到構造函數中,它不會給出錯誤。

import java.util.*; 

public class Test 
{ 
    static String pos_Let ; //letter coordinate for map 
    static int pos_Num;  // number coordinate for map 
    static int pos_LetNum ; //number reference of letter from HashMap let 

    Map o = new HashMap(); 
    o.put(6, "O"); 
    o.put(7, "O"); 
    o.put(9, "O"); 
    o.put(10, "O"); 
    o.put(12, "O"); 

    Hashtable p = new Hashtable(); 
    p.put (10,"P"); 
    p.put (11,"P"); 
} 
+0

「但錯誤」並沒有告訴我們有關你得到的錯誤的任何信息。我*強烈*懷疑當您提供錯誤描述時,您會發現在Stack Overflow中搜索確切的錯誤消息會發現很多重複項。 –

+1

tibtof的答案是解決你的**當前**問題。但是你真正的問題是你現在的技術水平太快了。你不瞭解java類的基本結構;但是你已經「已經」添加諸如hashmaps之類的東西了。所以你遇到問題;給他們在這裏。換句話說:你期望這裏的人**訓練你。但這不是這個網站的意圖。我個人的建議:從超級小例子開始。鍵入它們,運行編譯器,執行它們。或者至少:像喬恩所說的那樣做。避免詢問以前數千次的問題。 – GhostCat

回答

3

您正在編寫方法或靜態/初始化塊之外的代碼。在Java中不允許這樣做。

對於一個快速測試,你可以使用的主要方法:如果你想定義的地圖爲場並將它初始化,您可以使用構造函數或初始化塊

public static void main(String[] args) { 
    Map o = new HashMap(); 
    o.put(6, "O"); 
    o.put(7, "O"); 
    o.put(9, "O"); 
    o.put(10, "O"); 
    o.put(12, "O"); 


    Hashtable p = new Hashtable(); 
    p.put (10,"P"); 
    p.put (11,"P"); 
} 

final Map<Integer, String> o; 

{ 
    o = new HashMap<Integer, String>(); 
    o.put(6, "O"); 
    o.put(7, "O"); 
    o.put(9, "O"); 
    o.put(10, "O"); 
    o.put(12, "O"); 
}