Reputation: 653
This is my code for finding the no. of vowels in a string:
{
String inyo=inpeo.getText().toLowerCase();
System.out.println(inyo); // Just checking for an empty string
int vowcount=0;
for(int i=0;i<=inyo.length();i++)
{
char rol=inyo.charAt(i);
if(rol=='o'||'u'==rol||rol=='a'||rol=='e'||rol=='i')
{
vowcount=vowcount+1;
System.out.println(vowcount);
}
numout.setText(""+vowcount);
}
}
Now, nothing is wrong with the output here-it finds the exact no. of vowels as I intended. But it gives me this error:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:646)
at WordCheck.jButton2ActionPerformed(WordCheck.java:147)
// Extra errors removed as they're irrelevant to my issue
As a result, there is no way of reusing the program other than closing and restarting it. when the output is coming out as desired, why am I getting this error? I don't get any empty Strings, either.
Upvotes: 2
Views: 1223
Reputation: 172378
The for loop should be
for(int i=0; i<inyo.length(); i++)
Presently when it goes to the last iteration the index of the string is 4 whereas inyo.length()
is 5. Hence it results in out of bounds.
Upvotes: 1
Reputation: 201409
Your for
loop is going one too far, this
for(int i=0;i<=inyo.length();i++)
should be
for(int i=0;i<inyo.length();i++)
Note that when i == invo.length()
it's passed the end of the array, because Java starts indexing with 0
.
Upvotes: 1
Reputation: 36304
i<=inyo.length()
here. The String index starts from 0. The length count starts from one. So, the last index of a String is 4 when its length is 5.
It should be
i<inyo.length()
Upvotes: 3
Reputation: 72844
The last iteration of the for
loop is causing the exception (when i == inyo.length()
). Simply replace it with:
for(int i=0; i<inyo.length(); i++)
Upvotes: 3