簡體   English   中英

Java替換所有字符串,替換所有小於3的數字

[英]Java replace all string, replacing all numbers less than 3

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(“ number ”,“”)'替換所有小於或等於4的數字呢? 創建一個新的.replaceAll 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
[D@12452e8
        ^
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)

要解決您的錯誤,您只需更換

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM