2

So, I was writing a simple program to enter a string and count the total no. of m. So, here's my code

for(int i=0; i<=n; i++)
    {
        if((str.charAt(i)=='m'))
        {
        } else {
            count++;
        }
    }
    System.out.println("The total number of m is "+count);

where n=str.length(); and str is a string which I had taken but there this error which keeps coming

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14
at java.lang.String.charAt(String.java:646)
at javaapplication.JavaApplication.main(JavaApplication.java:28
Java Result: 1

what's this error and how to remove it?

1
  • The count++ should be in the if block, not the else block, since you are trying to count the number of m's. Commented Feb 22, 2016 at 10:50

5 Answers 5

6

A String of length() == n has valid indices from 0 to n-1;

Change

for(int i=0; i<=n; i++)

to

for(int i=0; i<n; i++)
Sign up to request clarification or add additional context in comments.

Comments

1

Imagine you have the following array of length 7:

-----------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |  <-- Array index
-----------------------------
|10 |20 |30 |40 |50 |60 |70 |  <-- Array values
-----------------------------

A for loop of for(int i=0; i<=n; i++) in this case will loop 8 times iterating from index 0 to 7.

But the array element at index 7 does not exist, hence giving outOfBoundsException.

Where as a for loop of for(int i=0; i<n; i++) will loop 7 times iterating from 0 to 6.

Comments

0

Remember Strings are indexed from 0 to StringName.length() - 1. Since you are iterating through StringName().length -- you are actually going right outside the "bounds" of the string which is causing the error. You need to make sure your indices are correct in your for loop.

Comments

0

Characters in String variable start at 0 index.

Also if you want to count the total appearance of small letter m, move your count++ to your if block statement.

 n=str.length() - 1;
    for(int i=0; i<=n; i++)
        {
            if((str.charAt(i)=='m'))
            {
                  count++;
            }
        }
        System.out.println("The total number of m is "+count);

Comments

0

charat works with index(works from to n-1), but in your for you get to condition where you have i=n, in this case charat throws exception because it does not have that index in array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.