javastringexceptionprocessingcharat

StringIndexOutOfBoundsException - Processing


I'm trying to build a function that when given a string and a starting point will return whatever number is before the delimiter (', '). So if it was handed ("45,621,9", 0) it returns 45.

This is what I have, and it works great until you hit the end of the string and then it throws a StringIndexOutOfBoundsException with String index out of range: 8.

So if I try with ("45,621,9", 7), I get that error. How can I handle the end of string and stop the loop? I thought of using a null check but since char is primitive I can't.

final char delim = ',';
char dataStorage;

int nextItem (String data, int startFrom) {
  String dataValue = "";
  for (int i = startFrom; i < delim; i++) {
    dataStorage = data.charAt(startFrom);
    if (dataStorage != delim) {
      dataValue = dataValue + dataStorage;
      startFrom ++;
    }
  }
  startFrom++;
  return Integer.parseInt(dataValue);
}

Right now if I call nextItem("45,621,9", 7) I get that exception when it should return 9 and then stop the loop.


Solution

  • See the comment from Jon Skeet. Your for loop is not correct. Correct it like below and try:-

    for (int i = startFrom; i < data.length(); i++){
            dataStorage = data.charAt(i);
              if(dataStorage != delim){
                  dataValue = dataValue + dataStorage;
                  i++;
              }