0

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.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Carter
  • 25
  • 4
  • Your loop condition really doesn't make sense: `for (int i = startFrom; i < delim; i++)`. Isn't `i` mean to be the *index into the string*. Why would you compare it with the Unicode value of the delimiter you're looking for? And why are you not actually using the value of `i` within the body of the loop? Currently that's a very odd-looking loop. I suspect you should really be using substring rather than string concatenation, and that your loop should be using `for (int i = startFrom; i < data.length(); i++)` for starters. – Jon Skeet Nov 19 '17 at 22:37
  • please add tag with language name – derloopkat Nov 19 '17 at 22:38

1 Answers1

-1

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++;
          }
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17