# Array out of bounds

• 01-01-2006, 09:51 AM
stormswimmer
Array out of bounds
Can anyone tell me why i am getting a java.lang.ArrayIndexOutOfBoundsException: 4
at Piglatinator.calculateVowelPositions(Piglatinator.java:53)
What this method is trying to do is calulate the vowel positions of a string entered by a user.

Code:

```    public static int calculateVowelPositions(String str) throws ArrayIndexOutOfBoundsException     {         str = str.toLowerCase();         str = str.trim();         int vowelPositions [] = new int [4];         {             vowelPositions [0] = str.indexOf('a');             vowelPositions [1] = str.indexOf('e');             vowelPositions [2] = str.indexOf('i');             vowelPositions [3] = str.indexOf('o');             vowelPositions [4] = str.indexOf('u');         }          int position = 0;         for(int i = 0; i < vowelPositions.length + 1; i ++)         {             position = Math.min((int) vowelPositions[i -1], (int) vowelPositions [i]);         }         return position;     }```
• 01-01-2006, 01:03 PM
destin
The size of the array doesn't mean 0-4, it means it has a size of 4 (0, 1, 2, 3, the first 4 numbers, starting at 0). If you have an array with size 7, it would be 0, 1, 2, 3, 4, 5, 6.

an easier way to do what you're trying to do would be:
Code:

`char vowelPositions [] = { 'a', 'e', 'i', 'o', 'u' };`
which does the same thing that you have up there.
• 01-01-2006, 09:55 PM
destin
Quote:

Code:

```for(int i = 0; i < vowelPositions.length + 1; i ++) {     position = Math.min((int) vowelPositions[i -1], (int) vowelPositions [i]); }```

You're looping way too many times, which will result in more ArrayIndexOutOfBoundsExceptions.

Your for loop is doing the same thing as this:
Code:

```// ArrayIndexOutOfBoundsException: -1 position = Math.min(vowelPositions[-1], vowelPositions[0]); position = Math.min(vowelPositions[0], vowelPositions[1]); position = Math.min(vowelPositions[1], vowelPositions[2]); position = Math.min(vowelPositions[2], vowelPositions[3]); // ArrayIndexOutOfBoundsException: 4 position = Math.min(vowelPositions[3], vowelPositions[4]);```
I have no idea how this method relates to what you're trying to do though...

Here's a method that will return an array containing 1s and 0s, 1s meaning a vowel is in that position and 0 meaning not a vowel. for example, apple would be: 1 0 0 0 1
Code:

```public static int[] vowelPositions(String str) {     /** will store the positions of vowels in str */     int[] positions = new int[str.length()];             for (int i = 0; i < positions.length; i++) {         switch(str.toLowerCase().charAt(i)) {         case 'a':         case 'e':         case 'i':         case 'o':         case 'u':             positions[i] = 1;             break;         default:             positions[i] = 0;             break;         }     }     return positions; }```
I haven't compiled the code above yet, but it should work.