Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

StringIndexOutOfBoundsException when trying to count 'a's in the entered word in Java

public class methods {
    public static int howMany(String word) {
        char character = 'a';
        int a = 0;
        for (int i=0;i<=word.length();i++) {
            if (word.charAt(i)==character) {
                a++;
            }
        }
        return a;
    }
    public static void main(String[] args) {
        System.out.println(howMany("afdfaf"));
    }
}

code gives error.
please help.
I couldn’t find where is the error.

Expected output:

2

Observed error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6

The exception happens in this line:

    if (word.charAt(i)==character) {

>Solution :

Change this line, you are exceeding the word length

Rewrite:

for (int i=0;i<=word.length();i++)

into

for (int i=0;i<word.length();i++)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading