简体   繁体   中英

Java - String Index Out of Bounds Exception

I'm getting the following exception on the line where head is assigned and I'm not sure why:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 44

When using "{1,2},3" as the value of s , running a debugger I can follow the loop and it is correctly assigning commaSpot to be 5 as I think it should. But for some reason s.charAt(commaSpot)) doesn't think 5 is a valid index even though s is 7 characters long.

int commaSpot = 0;
int bracePairs = 0;
for(int i = 0; i < s.length(); i++) {
   if(s.charAt(i) == '{') bracePairs++;
   if(s.charAt(i) == '}') bracePairs--;
   if(s.charAt(i) == ',' && bracePairs == 0) {
      commaSpot = i;
      break;
   }
}
head = s.substring(0, s.charAt(commaSpot));
tail = s.substring(s.charAt(commaSpot), s.length());

The problem is that you're using the result of s.charAt(commaSpot) as the second argument - rather than commaSpot itself. You want:

head = s.substring(0, commaSpot);
tail = s.substring(commaSpot, s.length());

You don't care about the value of the string at commaSpot - or rather, you know that it's a comma (Unicode value 44, hence the exception message). You care about the value of commaSpot itself, which is the place you want to split on.

In these line

head = s.substring(0, s.charAt(commaSpot));
tail = s.substring(s.charAt(commaSpot), s.length());

s.charAt(commaSpot) returns a char that is handled as an int for the index position. You want to use the actual index, which is i , so keep and use a copy of that value ( commaspot ).

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