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

Java使用split按逗号分割字符串报ArrayIndexOutOfBoundsException如何解决

错误原因
  • Scanner的nextInt()方法只会读取输入的整数内容,不会处理整数后方的换行符。你读取完第一行的整数N后,输入缓冲区内仍残留第一行末尾的换行符
  • 第一次循环执行sc.nextLine()时,会直接读取到这个残留的空换行字符串,对空串/只有换行的字符串执行split(",")后得到的数组长度为1,访问n[1]自然就触发数组下标越界异常
解决方案

有两种常用修复方式:

方式1:读取整数后手动吃掉残留换行

调用完nextInt()后额外执行一次sc.nextLine(),把缓冲区里的换行符清空,再进入循环读取后续行。
修改后代码如下:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    sc.nextLine(); // 新增这行,吃掉nextInt剩余的换行符
    int max = 0;
    String batsman = "";
    
    for(int i =0; i< N; i++){
        String a = sc.nextLine();
        String[] n = a.split(",");
        int b = Integer.parseInt(n[1]);
        
        if (b > max){
            max = b;
            batsman = n[0];
        }
    }
    
    System.out.print(batsman);
}

方式2:所有输入统一用nextLine读取

避免混用nextInt()和nextLine(),第一行直接用nextLine()读取再转成整数,从根源上避免换行残留问题。
修改后代码如下:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = Integer.parseInt(sc.nextLine()); // 直接读整行转整数
    int max = 0;
    String batsman = "";
    
    for(int i =0; i< N; i++){
        String a = sc.nextLine();
        String[] n = a.split(",");
        int b = Integer.parseInt(n[1]);
        
        if (b > max){
            max = b;
            batsman = n[0];
        }
    }
    
    System.out.print(batsman);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:24:02