当我尝试从文件中拆分一行时,我不断收到 IndexOutOfBounds 错误

I keep getting IndexOutOfBounds error when I try to split a line from a file

那么首先大家好!我正在尝试逐行读取文件并拆分该行,以便我可以将结果子字符串用作特定函数的参数。我知道它在达到 "Min units consumed:" 时失败了。我也尝试将零件(下图第一张)修复为 null 但它不起作用。我知道这个错误,但我不知道如何解决它。如果有帮助就太棒了,干杯!

虽然你应该调试你的代码来找到你的 parts 数组里面携带了什么,但是为了避免出现 IndexOutofBoundException,你应该以更安全的方式编写代码,有点像这样,

    System.out.println("currentLine: " + currentLine); // print the contents of currentLine too
    parts = currentLine.split(": ");
    if (parts.length >= 2) {
        System.out.println(parts[0] + " " + parts[1]);
    }

这样做

String[] split = currentLine.split(":");
for (int i = 0; i < split.length; i++)
    split[i] = split[i].replaceFirst(" ", "").trim();