-2

Given a string, print the number of alphabets present in the string. Input: The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.Each test case contains a single string. Output: Print the number of alphabets present in the string.

This is a question i have been trying to solve this question on eclipse but it keeps throwing ArrayIndexoutOfBoundsException in line 7 of my code. I tried understanding what i've done wrong but i have not been able to. Could some one please explain whats wrong here . I have attached the code.

public class solution {
    public static void main(String[] args){
        String s = "baibiasbfi" ;
        int count =0; 
        for(int i=0;i<=s.length();i++){
            char[] a= s.toCharArray();
            if(a[i]>='a'&& a[i]<='z'||a[i]>='A'&&a[i]<='Z')
                count++;}
    System.out.println(count);  
    }
}
jenygeorge
  • 11
  • 4
  • 1
    to avoid this exception use i – Vaseph Feb 05 '16 at 07:51
  • Basically what ArrayIndexOutOfBoundsException means is that you're trying to access a position of your array `a` that's beyond access. In this case, your string `baibiasbfi` has 10 characters which means that you can access it from position 0 to 9. When you're doing `i <= s.length()`, and since `s.length` is equal to the size of the array which is 10, you're trying to access the position 10 of the array which is beyond reach. To solve it, remove the `=` from your condition `i <= s.length()` and you'll have your problem solved. – António Ribeiro Feb 05 '16 at 08:00

2 Answers2

0
i <= s.length();

in your for loop should be:

i < s.length();

ArrayIndexOutOfBoundsException is thrown:

to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23
0

In java, arrays are from 0 to length-1. You are using your loop compare it with i<=s.length(). This means your loop is giving back the length of the array. This gives a ArrayIndexoutofBoundsException.

Replace your loop with:

for(int i=0;i<s.length();i++){
Ferrybig
  • 18,194
  • 6
  • 57
  • 79