You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将String转为int?求解NumberFormatException异常处理方法

解决String转int时的NumberFormatException问题

嘿,我来帮你搞定这个问题~你遇到的NumberFormatException原因很明确:你生成的字符串str里包含了非数字的文本内容(比如"Current Minutes : "),而Integer.valueOf()只能解析纯数字组成的字符串,所以直接转换肯定会报错。

我给你两种解决方案,按需选择:

方案一:从现有字符串中提取数字部分

如果一定要保留当前的字符串格式,我们可以把字符串里的数字提取出来再转换:

方法1:用正则表达式过滤非数字字符

import java.util.Date;
class DateDemo {
    public static void main(String args[]) {
        Date date = new Date();
        String str = String.format("Current Minutes : %tM", date );
        try {
            // 过滤掉所有非数字字符,得到纯数字字符串
            String numStr = str.replaceAll("[^0-9]", "");
            int a = Integer.valueOf(numStr);
            System.out.print(a);
        } catch(NumberFormatException e) {
            // 捕获异常后可以做友好提示,比如打印错误信息
            e.printStackTrace();
        }
    }
}

方法2:按固定格式分割字符串

因为你的字符串格式是固定的("Current Minutes : 数字"),可以直接按:分割,取后面的部分再去除空格:

import java.util.Date;
class DateDemo {
    public static void main(String args[]) {
        Date date = new Date();
        String str = String.format("Current Minutes : %tM", date );
        try {
            // 按冒号分割,取第二部分并去除前后空格
            String numStr = str.split(":")[1].trim();
            int a = Integer.valueOf(numStr);
            System.out.print(a);
        } catch(NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

方案二:直接获取分钟的int值(更推荐)

其实完全没必要先把分钟转成字符串再转int,我们可以直接从日期对象中获取分钟的数值,这种方式更高效也更安全:

Java 8+ 推荐用法(使用java.time包,线程安全)

import java.time.LocalDateTime;
class DateDemo {
    public static void main(String args[]) {
        LocalDateTime now = LocalDateTime.now();
        int minutes = now.getMinute();
        System.out.println("Current Minutes : " + minutes);
    }
}

旧版Java用法(使用Calendar类)

如果你的项目还在使用Java 8以前的版本,可以用Calendar类:

import java.util.Calendar;
class DateDemo {
    public static void main(String args[]) {
        Calendar cal = Calendar.getInstance();
        int minutes = cal.get(Calendar.MINUTE);
        System.out.println("Current Minutes : " + minutes);
    }
}

小提醒

  • 以后做String转int的时候,一定要确保待转换的字符串是纯数字(可以包含正负号,但不能有字母、空格或其他符号)
  • 记得始终捕获NumberFormatException,避免程序崩溃,还可以在catch块里给用户或开发者友好的提示
  • Java 8及以后尽量使用java.time包下的日期时间类,比旧的Date和Calendar类更易用、线程安全

内容的提问来源于stack exchange,提问作者Umar Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:58:47