Search code examples
javaexceptionfor-loopruntime-errorjava.lang.class

String index out of bounds? Where?


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.


Solution

  • 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++)