2013-01-03 124 views
0
public static enum pie { 
    APPLE_PIE1(1, 250), 
    PUMPKIN_PIE1(2, 300), 
    OTHER_PIE1(3, 350), 
    APPLE_PIE2(4, 400), 
    OTHER_PIE2(5, 450), 
    PUMPKIN_PIE2(6, 500), 
    APPLE_PIE3(7, 550), 
    ; 
    private static Map<Integer, pie> pie = new HashMap<Integer, pie>(); 
    static { 
     for(pie pie : pie.values()) { 
      pie.put(pie.getId(), pie); 
     } 
    } 

    public static pie forId(int id) { 
     return pie.get(id); 
    } 

    private pie(int id, double exp) { 
     this.id = id; 
     this.exp = exp; 
    } 

    public int id; 
    public double exp; 


    System.out.println("My favorite type of pie is " + pie.toString().toLowerCase().replaceAll("_", " ").replaceAll("2", "").replaceAll("3", "").replaceAll("4", "") + "."); 

示例代碼撕掉了,但我怎麼會作出這樣的「.replaceAll(‘’,‘’)」取代小於或等於所有的數字4用更簡單的代碼?創建一個新的.replaceAll 3次是多餘的。如果我這樣做...:Java的替換所有的字符串,替換所有數字低於3

double number[] = {1, 2, 3, 4}; 

    pie.toString().toLowerCase().replaceAll("_", " ").replaceAll(number.toString(), "") + "."); 

...我會得到一個討厭的錯誤。

這裏的錯誤...

SEVERE: An error occurred in an executor service! The server will be halted immediately. 
java.util.regex.PatternSyntaxException: Unclosed character class near index 9 
[[email protected] 
     ^
at java.util.regex.Pattern.error(Unknown Source) 
at java.util.regex.Pattern.clazz(Unknown Source) 
at java.util.regex.Pattern.sequence(Unknown Source) 
at java.util.regex.Pattern.expr(Unknown Source) 
at java.util.regex.Pattern.compile(Unknown Source) 
at java.util.regex.Pattern.<init>(Unknown Source) 
at java.util.regex.Pattern.compile(Unknown Source) 
at java.lang.String.replaceAll(Unknown Source) 
+2

顯示你希望我們的錯誤 - 自己運行程序? – MrSmith42

+0

你確定你使用正確的語法嗎?最後一行似乎以一個隨機的')'結尾,我不認爲它應該在那裏。 – Patrickdev

回答

0

要改正錯誤,你應該更換

double number[] = {1, 2, 3, 4}; 

通過

String number = "[1, 2, 3, 4]"; 

但我不會用的replaceAll這樣做。相反,我會一個label字段添加到您的枚舉,以類似的方式爲其他領域,並呼籲getLabel()代替toString(),或覆蓋toString()返回標籤:

public static enum pie { 
    APPLE_PIE1(1, 250, "apple pie"), 
    PUMPKIN_PIE1(2, 300, "pumpkin pie"), 
    ... 

    private int id; 
    private double exp; 
    private String label; 

    private pie(int id, double exp, String label) { 
     this.id = id; 
     this.exp = exp; 
     this.label = label; 
    } 

    public String getLabel() { 
     return label; 
    } 

    // optional: I wouldn't do it as it would make debugging harder 
    @Override 
    public String toString() { 
     return label; 
    } 
} 
+0

非常感謝。 – Fridder

相關問題