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

Java大数求和代码触发NumberFormatException错误,如何修复?

问题原因与修复方案

错误原因

调用inp.nextInt()读取整数limit后,输入缓冲区中会残留一个换行符。第一次执行inp.nextLine()时,会读取这个空的换行符(即零长度字符串),而BigInteger的构造器无法解析空字符串,因此抛出java.lang.NumberFormatException: Zero length BigInteger。

修复方法

有两种常见的修复方式:

方法1:消费残留的换行符

在inp.nextInt()之后,额外调用一次inp.nextLine()来清空缓冲区中的换行符,确保后续的inp.nextLine()能正确读取每一行大数。

修复后的代码:

import java.util.Scanner;
import java.math.BigInteger;

public class LargeSum {

    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        int limit = inp.nextInt();
        inp.nextLine(); // 处理nextInt()留下的换行符
        BigInteger[] arr = new BigInteger[limit];
        
        for (int i = 0; i < limit; i++) 
            arr[i] = new BigInteger(inp.nextLine());
        
        BigInteger sum = arr[0]; // 直接使用已有BigInteger对象,无需重复转换
        for (int i = 1; i < limit; i++) 
            sum = sum.add(arr[i]);
        
        System.out.println(sum); // 输出求和结果
    }
}

方法2:统一使用nextLine()读取输入

直接用inp.nextLine()读取表示limit的整行内容,再转换为整数,避免缓冲区残留问题。

修复后的代码:

import java.util.Scanner;
import java.math.BigInteger;

public class LargeSum {

    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        int limit = Integer.parseInt(inp.nextLine()); // 读取整行并转为整数
        BigInteger[] arr = new BigInteger[limit];
        
        for (int i = 0; i < limit; i++) 
            arr[i] = new BigInteger(inp.nextLine());
        
        BigInteger sum = arr[0];
        for (int i = 1; i < limit; i++) 
            sum = sum.add(arr[i]);
        
        System.out.println(sum);
    }
}

额外优化点

原代码中BigInteger sum=new BigInteger(String.valueOf(arr[0]))属于冗余操作,arr[0]本身就是BigInteger对象,直接赋值即可。另外添加System.out.println(sum)可以输出最终的求和结果,否则程序运行后无法看到计算结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:43:14