Link to home
Start Free TrialLog in
Avatar of Dirk6996
Dirk6996

asked on

charAt(index) indexOutOfBoundsException HElp me Catch. Thanks?

I am trying to find and compare the values of a String by calling the charAt(index) but I am getting an indexOutOfBoundsException when the String ends I want to catch the exception and let the method from which I am invoking the charAt(index) call from end, once it finds the end of the String ie when it says indexOutOfBoundsException. I could catch the exception or write a new charAt() method that overwrites the String method. Help me?
ASKER CERTIFIED SOLUTION
Avatar of Ajay-Singh
Ajay-Singh

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dirk6996
Dirk6996

ASKER

Like this if(lengthOfString >= i)
if(i < string.length())
....
I am trying to find and compare the values of a String by calling the charAt(index) but I am getting an indexOutOfBoundsException when the String ends I want to catch the exception and let the method from which I am invoking the charAt(index) call from end,
....
Like the other people say.. if the index that you pass to charAt is bigger than the length of the string you will get an Exception.. so if you want to iterate thru the string (and use the charAt method to get the chars), you have to do something like this:

for (int i=0; i<string.length(); i++) {
   System.out.println(string.charAt(i));
}

....
once it finds the end of the String ie when it says indexOutOfBoundsException. I could catch the exception or write a new charAt() method that overwrites the String method. Help me?
....
If you want to iterate thru the string you have to do something like a I told you before.. otherwise.. if you want to know only the last character of the string you can do something simple like: string.charAt(string.length-1)