Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Index Out of Bounds Exception (Java)

Here is my code:

public class countChar {

    public static void main(String[] args) {
        int i;
        String userInput = new String();

        userInput = Input.getString("Please enter a sentence");

        int[] total = totalChars(userInput.toLowerCase());

        for (i = 0; i < total.length; i++);
        {
            if (total[i] != 0) {
                System.out.println("Letter" + (char) ('a' + i) + " count =" + total[i]);
            }
        }
    }

    public static int[] totalChars(String userInput) {
        int[] total = new int[26];
        int i;
        for (i = 0; i < userInput.length(); i++) {
            if (Character.isLetter(userInput.charAt(i))) {
                total[userInput.charAt(i) - 'a']++;
            }
        }
        return total;
    }
}

The program's purpose is to ask the user for a string, and then count the number of times each character is used in the string.

When I go to compile the program, it works fine. When I run the program, I am able to enter a string in the popup box, but after I submit the string and press OK, I get an error, saying

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at countChar.main(countChar.java:14)

I'm not completely sure what the problem is or how to fix it.

like image 523
Boxasauras Avatar asked Aug 31 '13 15:08

Boxasauras


People also ask

How do you stop an array out of bounds exception in Java?

In order to avoid the exception, first, be very careful when you iterating over the elements of an array of a list. Make sure that your code requests for valid indices. Second, consider enclosing your code inside a try-catch statement and manipulate the exception accordingly.

What happens if an array index goes out of bounds?

If we use an array index that is out of bounds, then the compiler will probably compile and even run. But, there is no guarantee to get the correct result. Result may unpredictable and it will start causing many problems that will be hard to find. Therefore, you must be careful while using array indexing.


2 Answers

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

With this semi-colon, the loop loops until i == total.length, doing nothing, and then what you thought was the body of the loop is executed.

like image 128
JB Nizet Avatar answered Nov 15 '22 20:11

JB Nizet


for ( i = 0; i < total.length; i++ ); // remove this
{
    if (total[i]!=0)
        System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}

The for loop loops until i=26 (where 26 is total.length) and then your if is executed, going over the bounds of the array. Remove the ; at the end of the for loop.

like image 27
Sotirios Delimanolis Avatar answered Nov 15 '22 18:11

Sotirios Delimanolis