简体   繁体   中英

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

Well first of all hello! I am trying to read a file line by line and split that line in such a way that I can use the resulted substrings as params' for specific functions. I know it fails when it reaches "Min units consumed:". I tried to fix parts (first image below) as null also but it doesn't work. I am aware of the error but I don't know how to fix it alternatively. Some help would be awesome, cheers!

在此处输入图片说明

在此处输入图片说明

Although you should debug your code to find what your parts array is carrying inside, but to avoid getting IndexOutofBoundException, you should write code in a safer way, somewhat like this,

    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]);
    }

Do this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM