0

I FINALLY have the map and points(arrays) working for my app. Quick question: I have a fatal exception with substring(), a "stringIndexOutOfBoundException"

In general, what is that referring to?

An I going past the end of a string using substring()?

Thanks,

Marc Brown
  • 601
  • 2
  • 11
  • 26

3 Answers3

1
testing.substring(1,2);

(I want to parse each character to find specific characters)

I wouldn't use substring() for grabbing 1-length strings (which is just a single character), but rather charAt(int) for specific positions. If you need to go over all characters in the string, you're probably better off with by converting the whole thing to a char[] first (using toCharArray()) and iterate over that.

MH.
  • 45,303
  • 10
  • 103
  • 116
0

Yes, you're going past the end of your strings bounds generally.

The Java API even tells you so...

IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

You should get used to using the API. It tells you what exceptions a method throws and why.

Try printing the Strings length and value before attempting substring. That'll help you see the problem.

For example...

String testing = "Hello StackOverflow";
System.out.println("Length of testing = " + testing.length);
System.out.println("Value of testing = " + testing);
testing.substring(1,2);
Aidanc
  • 6,921
  • 1
  • 26
  • 30
  • Does the beginning index have to start with 1, I used 0 as the beginning index. The second parameter of substring is 1 (I want to parse each character to find specific characters), i.e. `variable.substring(0,1);` Should this be `variable.substring(1,2);` ? – Marc Brown Apr 23 '12 at 00:03
  • I didn't understand fully how substring in Java works. In PHP, the end index tells you HOW MANY characters it will capture, not where it will stop. In JAVA the second parameter tells you where to stop, not how many characters to pick up after beginning index. Thanks – Marc Brown Apr 23 '12 at 00:25
0

Like stated in the official doc here:

public String substring(int beginIndex)

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

Community
  • 1
  • 1
a.bertucci
  • 12,142
  • 2
  • 31
  • 32