Skip to content
Advertisement

How to get the maximum occurring character and its occurrences from a user inputted String sentence?

I have a program that asks the user for a String sentence and output its maximum occuring character and its occurences.

My issue here is that the function that counts the max character and its occurrences only counts that maximum character and its occurrences only for a single word(that is all lowercase) and not a full sentence or a word that starts with an uppercase.

If the user inputs a sentence, the program keeps having an index out of bounds in the freqLetter array (frequent letter array) in which I have no idea why it undergoes an out of bounds, does it have something to do with the whitespaces of the sentence? Should I create another loop in iterating the array or should I make another array?? (I am sometimes confused in manipulating indexes of arrays).

Code:

static void maxOccuringChar(char str[]) {    // function that counts that max character and its occurences
    char maxChar = ' ';

    int freqLetter[] = new int[26];
    int lengthString = str.length;
    int maximum = -1;


    for (int i = 0; i < lengthString; i++)
        freqLetter[str[i] - 'a']++;    // I'm not sure why it becomes out of bounds for some reason


    for (int i = 0; i < 26; i++)
        if (maximum < freqLetter[i]) {
            maximum = freqLetter[i];
            maxChar = (char)(i + 'a');
        }

    System.out.print(maxChar + " = " + maximum); // returns result    
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    char[] StringInput = in.nextLine().toCharArray();   // user inputs the given String sentence and puts into character array

    maxOccuringChar(StringInput);  // calls function and returns the maximum character and and its occurences
}
Output 1:
Elephant
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -28 out of bounds 
for length 26

Output 2:
I am confused
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -24 out of bounds 
for length 26

Output 3:     // works fine here
hello
l = 2
Process finished with exit code 0

Your response would be highly appreciated and would indeed help me on this one!

Thank you very much everyone!!!

Advertisement

Answer

The problem occurs because the space code is 32. Change your loop to skip spaces

for (int i = 0; i < lengthString; i++) {
    if(str[i] == ' ') {
        continue;
    }
    freqLetter[str[i] - 'a']++;
}

ASCII Table

Also you can solve this using streams

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    String input = in.nextLine();

    System.out.println(input.chars()
            .mapToObj(x -> (char) x)
            .collect(Collectors.groupingBy(x -> x, Collectors.counting()))
            .entrySet()
            .stream()
            .max(Comparator.comparingLong(Map.Entry::getValue))
            .get());
}

Output:

123333
3=4

But it would count spaces as well. If you don’t want to, then add this line after mapToObj(...)

.filter(c -> c != ' ')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement