Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

StringBuilder replace query

807591Mar 10 2008 — edited Mar 10 2008
I am NEW to Java programming.

Attempting to search a password looking for the letter 'l' and replacing with '_'.
e.g. my password = "abcdlefg".

Partial code is as follows:

int startIndex = 0;
int endIndex = 0;

for (int i = 1; i <= password.length(); i++)
{
startIndex = password.indexOf("l", 0);
endIndex = startIndex + 1;
password.replace(startIndex, endIndex, "_");
}
return password;

I expected the startIndex = 4 and endIndex = 5 and then to replace the character starting at index position 4 but ending before index position 5 (i.e. character 'l') to be replaced with "_" but instead I get:
'Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1'.

Can someone please explain why this happens?

Thanks,
Ewizard....
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 7 2008
Added on Mar 10 2008
1 comment
191 views