Why do I get an exception in this simple loop?
Hey there guys. I'm new to loops and I'm trying to write a simple code that outputs the number of uppercase letters in a string. However, I get an exception when I run the code. What's wrong? Here is the code:
Code :
public class CountingMatches
{
public static void main(String[] args)
{
String str = "Hello, World!";
int upperCaseLetters = 0;
for (int i = 0; i <= str.length(); i++)
{
char ch = str.charAt(i);
if(Character.isUpperCase(ch));
{
upperCaseLetters++;
}
}
System.out.println(upperCaseLetters);
}
}
And this is the exception I get:
Quote:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 13
at java.lang.String.charAt(Unknown Source)
at CountingMatches.main(CountingMatches.java:11)
Thanks.
Re: Why do I get an exception in this simple loop?
for (int i = 0; i <= str.length(); i++)
str.length is = the index number of the last element + 1
Re: Why do I get an exception in this simple loop?
Like jps said, you're taking the number of the last element in your string, and adding 1 to it. You can solve this by simply saying either:
for(int i = 0; i <= str.length() - 1; i++)
or the one I think is better
for(int i = 0; i < str.length(); i++)