0
public class AssignmentChapter9
{
    public static void main(String[] args)
    {
        String words = Input.getString("Please enter a series of words with the spaces omitted.");
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        String inputWords = words.toLowerCase();
        int lcount[] = new int[26];
        char var1;
        char var2;

        for(int x = 0; x <= words.length(); x++)
        {
            var1 = words.charAt(x);

            for(int y = 0; y < 27; y++)
            {
                var2 = alphabet.charAt(y);

                if(var1 == var2)
                {
                    lcount[y] += 1;
                }

            }
        }

        for(int z = 0; z < 27; z++)
        {
            System.out.println("Letter " + alphabet.charAt(z + 1) + " count = " + lcount[z]);
        }
    }
}

I've been trying to write a program in java to identify how many times each character in the alphabet appears in a given string. I was able to successfully compile the program but after the user input is completed, it gives an out of bounds exception. Any help would be appreciated.

gamer8756
  • 9
  • 3

1 Answers1

0

In the last loop you are iterating from 0 to 27 and you are trying to access index z + 1 which could not work, since your alphabet has only 26 indices - correct is only z. So the correct code would be:

String alphabet = "abcdefghijklmnopqrstuvwxyz";
String inputWords = words.toLowerCase();
int lcount[] = new int[26];
char var1;
char var2;

for(int x = 0; x < words.length(); x++)
{
    var1 = words.charAt(x);
    for(int y = 0; y < alphabet.length(); y++)
    {
        var2 = alphabet.charAt(y);
        if(var1 == var2)
        {
            lcount[y] += 1;
        }
    }
}

for(int z = 0; z < alphabet.length(); z++)
{
    System.out.println("Letter " + alphabet.charAt(z) + " count = " + lcount[z]);
}

When you are iterating over arrays or lists use the length method and do not use constants! Whenever you extend your alphabet with e.g. !?+- your code will not work anymore. The length method guards your code from index out of bound errors.

You could also save some lines of code and make the code more readable using the for each loop construct:

String alphabet = "abcdefghijklmnopqrstuvwxyz";
int lcount[] = new int[26];

for (char character : words.toLowerCase().toCharArray())
{
    for(int y = 0; y < alphabet.length(); y++)
    {
        if(character == alphabet.charAt(y))
        {
            lcount[y] += 1;
        }
    }
}

for(int z = 0; z < alphabet.length(); z++)
{
    System.out.println("Letter " + alphabet.charAt(z) + " count = " + lcount[z]);
}
keenthinker
  • 7,645
  • 2
  • 35
  • 45