字符串转数字 java

admin 34 0

在Java中,你可以使用 `Integer.parseInt()` 或 `Double.parseDouble()` 等方法将字符串转换为数字,以下是一些示例:

public class Main {
    public static void main(String[] args) {
        String str = "123";
        int num = Integer.parseInt(str);
        System.out.println(num);  // 输出: 123

        str = "123.45";
        double d = Double.parseDouble(str);
        System.out.println(d);  // 输出: 123.45
    }
}

请注意,如果字符串不能转换为数字(例如,如果字符串包含非数字字符),这些方法将抛出 `NumberFormatException`,你可能需要使用 `try-catch` 块来处理这种异常,如下所示:

public class Main {
    public static void main(String[] args) {
        String str = "123abc";
        try {
            int num = Integer.parseInt(str);
            System.out.println(num);  // 输出: 123
        } catch (NumberFormatException e) {
            System.out.println("无法将字符串转换为整数");
        }
    }
}