2016-09-19 68 views
-2

對於我自己Logger類我想定義的地圖繪製的優先數回有意義的字符串類似如下:在類的外部定義Map時如何解決錯誤:「class,interface,or enum expected」?

static Map<int, String> map = new HashMap<int, String>(); 
map.put(2, "VERBOSE"); 
map.put(3, "DEBUG"); 
map.put(4, "INFO"); 
map.put(5, "WARN"); 
map.put(6, "ERROR"); 

我不知道是否有可能是自動完成這樣的功能?但我現在知道每一個功能。

不過,我定義了線只是我的類定義之前,然後我得到的錯誤:

Error:(14, 8) error: class, interface, or enum expected 

,不知道這意味着什麼(也許我不能在類外部聲明的變量?)。我也嘗試在類中定義映射,但是put方法無法解析。我還注意到,我還沒有導入Map模塊,AndroidStudio似乎也不需要Map模塊(即名稱'映射'不是紅色並加下劃線)。

我很困惑(像往常一樣);如果優先級值是6等,我只想得到一個字符串「錯誤」。

我在做什麼錯在我的情況...?

+2

不是int;使用Integer作爲密鑰。 – duffymo

+2

你的變量必須在一個類中。在Java中,一切都必須在一個類中。你的語句('map.put ...')必須在方法中。 – khelwood

+0

Google靜態初始化器。 –

回答

3

maybe I cannot declare variables outside a class?

正確。

用途:

class Foo { 
    static Map<Integer, String> PRIORITY_LABELS = new HashMap<>(); 

    static { 
    PRIORITY_LABELS.put(2, "VERBOSE"); 
    PRIORITY_LABELS.put(3, "DEBUG"); 
    PRIORITY_LABELS.put(4, "INFO"); 
    PRIORITY_LABELS.put(5, "WARN"); 
    PRIORITY_LABELS.put(6, "ERROR"); 
    } 

    // rest of class goes here 
} 

I also notice, that I have not imported a Map module, and AndroidStudio does not seem to require a Map module (i.e. the name 'Map' is not red and underlined).

這是因爲Android的Studio不知道如何處理的代碼做。一旦你將它們移動到課程中,然後 Android Studio會意識到您正在嘗試使用MapHashMap,並且會要求您導入它們。

+0

我在類中有'Map'和'HashMap',並且android沒有要求導入任何內容。無論如何,你的解決方案似乎工作...... – Alex

+0

@Alex:也許你有'import java.util。*;'或者批量導入一堆類和接口的東西,包括'Map'和'HashMap'。 – CommonsWare

+0

@CommonsWare你好先生,對不起評論之間請我需要一個邏輯到這個問題http://stackoverflow.com/questions/39576258/how-to-keep-user-logged-in-always-connected-with-server – 2016-09-20 07:00:26

相關問題