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

时间:2018-11-25 18:44:09

标签: java string split indexoutofboundsexception

首先,您好!我试图逐行读取文件并以某种方式拆分该行,以便可以将结果子字符串用作特定功能的参数。我知道它达到“最小消耗单位:”时会失败。我也尝试将零件(下面的第一张图片)修复为null,但不起作用。我知道该错误,但不知道如何解决。一些帮助会很棒,欢呼!

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

尽管您应该调试代码以查找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]);
    }

答案 1 :(得分:0)

这样做

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