Isaac Peterson
Isaac Peterson

Reputation: 3

Occurrences in char Array

I have this problem, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100 at Exercise_12_2.main(Exercise_12_2.java:28) When i am trying to just simply count the occurrences of the letters in a char array. I just cant seem to wrap my head around how to work it out. I have been at it for several hours. Please help get me on the right track.

input: a a a b b c !
Expected output:

Counts:
a    3
b    2
c    1

This is my code so far. Please help me.

import java.util.Scanner;

public class Exercise_12_2
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in); // Setup scanner

        char[] charArray = new char[100];
        int[] counts = new int[26];
        char tempinput = '?';

        System.out.print("Enter letters (or ! to quit): ");

        while (tempinput != '!')
        {
            tempinput = (input.next()).charAt(0);
            charArray[tempinput]++;

            for (int c = 'a'; c <= 'z'; c++)
            {
                for (int k = 0; k <= charArray.length; k++)
                {
                    if (c == charArray[k])
                    {
                        counts[c] += 1;
                    }
                }
            }
        }
    }
    public static void displayCounts(int[] counts)
    {
        for (int i = 0; i < counts.length; i++)
        {
            if ((i + 1) % 10 == 0)
            {
                System.out.println(counts[i] + " " + (char)(i + 'a'));
            }
            else
            {
                System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
            }
        }
    }
}

Upvotes: 0

Views: 58

Answers (3)

Elliott Frisch
Elliott Frisch

Reputation: 201537

This problem becomes much easier if you use an appropriate data structure. For example, I would use a Map<Character, Integer> to keep the count and then iterate that to display. Like,

Scanner input = new Scanner(System.in); // Setup scanner
System.out.print("Enter letters (or ! to quit): ");
Map<Character, Integer> map = new HashMap<>();
char ch;
while ((ch = Character.toLowerCase(input.next().charAt(0))) != '!') {
    map.put(ch, map.getOrDefault(ch, 0) + 1);
}
System.out.println("Counts:");
for (int c = 'a'; c <= 'z'; c++) {
    if (map.containsKey((char) c)) {
        System.out.printf("%c\t%d%n", c, map.get((char) c));
    }
}

Which I tested with your example input, and I get as requested:

Enter letters (or ! to quit): a a a b b c !
Counts:
a   3
b   2
c   1

Upvotes: 1

Pandey Amit
Pandey Amit

Reputation: 703

I think after creating the character array of [a, a, b c, d, !, ..], following code will be enough to calculate count for each alphabet [a-z].

for (int k = 0; k < charArray.length; k++)
    {
        char c = charArray[k];
        if (c >= 'a' && c <= 'z' )
        {
            counts[c - 'a'] += 1;
        }
    }

Upvotes: 0

Neil Locketz
Neil Locketz

Reputation: 4328

java.lang.ArrayIndexOutOfBoundsException: 100 means you are asking for the 101st element of an array with only 100 elements. Remember, java arrays are indexed starting with 0.

From that you might be able to tell why this line is broken:

for (int k = 0; k <= charArray.length; k++)

charArray.length is 100, so you run up until k is 101, meaning that you try charArray[100] which is asking for the 101st element of charArray, but charArray only has 100 elements.

If you switch k <= charArray.length to k < charArray.length you should get farther.

On an unrelated note, counts[c] += 1; won't work. The int val of a char is its ascii value. The letter a for example is 97, so you'll go way off the end of your counts array. This also doesn't account for upper/lower case (which have different numeric values).

Upvotes: 1

Related Questions