溫馨提示×

Java中parseInt怎樣處理非法輸入

小樊
81
2024-10-10 17:00:55
欄目: 編程語言

在Java中,使用Integer.parseInt()方法將字符串解析為整數(shù)時,如果輸入的字符串不符合整數(shù)的格式,該方法會拋出一個NumberFormatException。為了處理這種非法輸入,你可以使用try-catch語句捕獲異常并進行相應(yīng)的處理。

下面是一個簡單的示例:

public class ParseIntegerExample {
    public static void main(String[] args) {
        String input = "123abc"; // 這是一個非法的整數(shù)字符串

        try {
            int result = Integer.parseInt(input);
            System.out.println("解析結(jié)果: " + result);
        } catch (NumberFormatException e) {
            System.out.println("非法輸入: " + input);
            System.out.println("錯誤信息: " + e.getMessage());
        }
    }
}

在這個示例中,我們嘗試將一個包含非數(shù)字字符的字符串解析為整數(shù)。由于輸入的字符串不符合整數(shù)的格式,Integer.parseInt()方法會拋出一個NumberFormatException。我們使用try-catch語句捕獲這個異常,并在catch塊中輸出一條錯誤信息。

0