溫馨提示×

如何處理valueOf方法可能拋出的異常

小樊
129
2024-09-02 17:22:03
欄目: 編程語言

當使用valueOf方法將字符串轉換為數值時,如果字符串不是有效的數值表示,那么該方法可能會拋出異常

  1. 使用try-catch語句捕獲異常:
public static void main(String[] args) {
    String str = "not a number";
    try {
        int num = Integer.valueOf(str);
        System.out.println("The number is: " + num);
    } catch (NumberFormatException e) {
        System.err.println("Invalid input: " + e.getMessage());
    }
}
  1. 在調用valueOf方法之前,使用正則表達式或其他方法驗證字符串是否為有效的數值表示。例如,使用matches方法和正則表達式:
public static void main(String[] args) {
    String str = "not a number";
    if (str.matches("^-?\\d+$")) {
        int num = Integer.valueOf(str);
        System.out.println("The number is: " + num);
    } else {
        System.err.println("Invalid input: not a valid number");
    }
}

這樣一來,在調用valueOf方法之前,你就可以確保字符串是一個有效的數值表示,從而避免拋出異常。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女