java.lang.ArrayIndexOutOfBoundsException: 26

Michael McKeehan :

I am currently learning Java, and when I am running example code from my learning material I am getting an "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26"

package com.java24hours;

public class Wheel {
    public static void main(String[] arguments) {
        String phrase[] = {
                "A STITCH IN TIME SAVES NINE",
                "DON'T EAT YELLOW SNOW",
                "EVERY GOOD BOY DOES FINE",
                "I WANT MY MVT",
                "PLAY IT AGAIN, SAM",
                "FROSTY THE SNOWMAN",
                "ONE MORE FOR THE ROAD",
                "HOME FIELD ADVANTAGE",
                "SHEFFIELD WEDNESDAY",
                "GOVER CLEAVLAND OHIO",
                "ZELDA: MAJORAS MASK",
                "SPEGHETTI WESTERN",
                "TEEN TITANS GO",
                "IT'S A WONDERFUL LIFE",
        };
        int [] letterCount = new int [26];
        for(int count = 0; count < phrase.length; count++) {
            String current = phrase[count];
            char[] letters = current.toCharArray();
            for(int count2 = 0; count2 < letters.length; count2++) {
                char lett = letters[count2];
                if ( (lett >= 'A') & (lett <= 'Z')) {
                    letterCount[lett - 'A']++;
                }
            }
        }
        for (char count = 'A'; count <= 'z'; count++) {
            System.out.print(count + ": " + 
                    letterCount [count - 'A'] + " ");
            if (count == 'M') {
                System.out.println();
            }

        }
        System.out.println();
    }
}

I am getting the correct output as far as the program goes, but I am unsure why the exception comes up.

By reading other threads I know that for a Java that an array starts with a "0" and when I tried to change the "26" to a "25" it would cause the program not to run. I am wanting to know if the exception that I am getting is actually an issue, or is it Java telling me that there are unused parts of the array since the array is actually reading that it should be 27 characters long and there is not a value for one.

Gatusko :

The code is trying to go to 'A' to 'z'. You need to go for 'A' to 'Z' Check for the ASCII TABLE

for (char count = 'A'; count <= 'Z'; count++) {
            System.out.print(count + ": " +
                    letterCount [count - 'A'] + " ");
            if (count == 'M') {
                System.out.println();
            }

        }

With this change the out put will be

A: 22 B: 1 C: 2 D: 12 E: 31 F: 8 G: 6 H: 7 I: 15 J: 1 K: 1 L: 10 M: 9 
N: 18 O: 20 P: 2 Q: 0 R: 9 S: 16 T: 19 U: 1 V: 6 W: 7 X: 0 Y: 7 Z: 1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117266&siteId=1