简体   繁体   中英

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.

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

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()

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM