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

为何Integer.parseInt会抛出NumberFormatException异常?

为何Integer.parseInt会产生如下错误?

代码示例

public static void main(String[] args) {
    String input = "6";
    Pattern pattern = Pattern.compile("[0-9]*");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String str = matcher.group();
        System.out.println(Integer.parseInt(str));
    }
}

异常信息

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:675)
at java.base/java.lang.Integer.parseInt(Integer.java:781)

问题原因

问题出在正则表达式[0-9]*的匹配规则上:*表示匹配0次或多次数字字符。当匹配字符串"6"时,matcher.find()会触发两次匹配:

  • 第一次匹配到目标数字"6",这是符合预期的结果;
  • 第二次匹配到字符串末尾的空字符串——因为*允许0次匹配,当指针移到"6"之后的位置时,空字符串满足"0次数字"的匹配条件,因此会被捕获。

当循环执行到第二次匹配时,matcher.group()返回空字符串"",而Integer.parseInt无法解析空字符串,直接抛出NumberFormatException。

解决办法

把正则表达式替换为[0-9]+,+表示匹配1次或多次数字字符,这样只会捕获非空的数字字符串,避免空字符串的匹配。修改后的代码如下:

public static void main(String[] args) {
    String input = "6";
    Pattern pattern = Pattern.compile("[0-9]+");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String str = matcher.group();
        System.out.println(Integer.parseInt(str));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:55:09