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

使用ArrayList处理文件列数据时遇索引越界异常的解决方案

问题解决:读取间隔排列字母并整理成列的Java异常处理

需求

从数据文件里按固定间隔提取字母,整理成垂直排列的列(后续要打乱列,所以不用普通数组)。数据文件内容:

[J]             [F] [M]            
[Z] [F]     [G] [Q] [F]            
[G] [P]     [H] [Z] [S] [Q]        
[V] [W] [Z] [P] [D] [G] [P]        
[T] [D] [S] [Z] [N] [W] [B] [N]    
[D] [M] [R] [J] [J] [P] [V] [P] [J]
[B] [R] [C] [T] [C] [V] [C] [B] [P]
[N] [S] [V] [R] [T] [N] [G] [Z] [W] 

报错情况

运行代码时第18行一直报索引越界:

 java -classpath .:target/dependency/* Main
[J]             [F] [M]            
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
    at java.base/java.util.Objects.checkIndex(Objects.java:359)
    at java.base/java.util.ArrayList.get(ArrayList.java:427)
    at Main.main(Main.java:18)

现有代码

import java.util.*;
import java.io.*;
public class Main {
public static void main(String [] args) throws FileNotFoundException{
   String line; 
   ArrayList<String> C = new ArrayList<>();
   String a = "";
   Scanner input = new Scanner(new File("dat.dat"));
   while (input.hasNextLine()) {
       line = input.nextLine();
     if (line.indexOf("[") != -1)
     {
       System.out.println(line);
       a = "";
       for(int lcv = 1; lcv < line.length() - 1; lcv+= 4)
         {
           a = line.substring(lcv, lcv+1);
           C.set(lcv/4, C.get(lcv/4) + a);
         }
     }
     }
}

问题分析与修复

问题根源

你初始化的ArrayList<String> C是空集合,第一次循环处理lcv=1时,lcv/4=0,此时调用C.get(0),集合里根本没有索引0的元素,直接触发了索引越界异常。

修复代码

修改核心逻辑:在访问指定列索引前,先确保集合长度足够,不足就补空字符串;最后添加输出逻辑得到预期格式。修改后的完整代码:

import java.util.*;
import java.io.*;
public class Main {
    public static void main(String [] args) throws FileNotFoundException{
        String line; 
        ArrayList<String> columns = new ArrayList<>();
        Scanner input = new Scanner(new File("dat.dat"));
        
        while (input.hasNextLine()) {
            line = input.nextLine();
            if (line.indexOf("[") != -1) {
                System.out.println(line);
                for(int lcv = 1; lcv < line.length() - 1; lcv += 4) {
                    String currentChar = line.substring(lcv, lcv+1);
                    int colIndex = lcv / 4;
                    
                    // 确保当前列索引在集合范围内,不够就补空字符串
                    while (colIndex >= columns.size()) {
                        columns.add("");
                    }
                    
                    // 把当前字符拼到对应列的末尾
                    columns.set(colIndex, columns.get(colIndex) + currentChar);
                }
            }
        }
        input.close();
        
        // 输出整理好的列
        System.out.println("\n整理结果:");
        for(String col : columns) {
            System.out.println(col);
        }
    }
}

关键修改说明

  1. 集合补全:用while循环检查当前列索引是否超出集合长度,不足就添加空字符串,避免索引越界。
  2. 字符拼接:把每一行对应位置的字符追加到对应列的字符串末尾,保证列的顺序和原文件从上到下一致。
  3. 输出逻辑:遍历集合直接输出每一列的字符串,得到垂直排列的格式。

预期输出

JZGVTDBN
 FPWDMRS
   ZSRCV
 FQZDNJCT
MFSGWPVN
  QPBVCG
    NPBZ
     JPW

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:06:01