溫馨提示×

Java parseInt方法如何處理字符串后綴

小樊
81
2024-10-10 17:57:58
欄目: 編程語言

parseInt 方法是 Java 中用于將字符串解析為整數(shù)的靜態(tài)方法。當(dāng)輸入的字符串包含非數(shù)字字符時,parseInt 會拋出 NumberFormatException。為了處理字符串后綴,你可以在調(diào)用 parseInt 之前對字符串進(jìn)行檢查和預(yù)處理。

以下是一個簡單的示例,展示了如何在解析字符串之前檢查并移除后綴:

public class Main {
    public static void main(String[] args) {
        String input = "123abc";
        try {
            int result = parseIntWithSuffix(input);
            System.out.println("Parsed integer: " + result);
        } catch (NumberFormatException e) {
            System.out.println("Invalid input: " + input);
        }
    }

    public static int parseIntWithSuffix(String input) {
        // 檢查字符串是否包含非數(shù)字字符
        if (!input.matches("^-?\\d+([eE][-+]?\\d+)?$")) {
            throw new NumberFormatException("Invalid input: " + input);
        }

        // 移除后綴(如果存在)
        String cleanedInput = input.replaceAll("[^0-9]", "");

        // 解析整數(shù)
        return Integer.parseInt(cleanedInput);
    }
}

在這個示例中,我們首先使用正則表達(dá)式檢查字符串是否僅包含數(shù)字(包括負(fù)數(shù)和科學(xué)計數(shù)法表示)。如果字符串包含非數(shù)字字符,我們拋出一個 NumberFormatException。接下來,我們使用 replaceAll 方法移除字符串中的所有非數(shù)字字符。最后,我們使用 Integer.parseInt 方法解析處理后的字符串。

請注意,這個示例僅適用于整數(shù)解析。如果你需要解析浮點(diǎn)數(shù)(如 Double.parseDouble),你需要相應(yīng)地調(diào)整正則表達(dá)式和后綴處理。

0