Calculate the frequency of characters in a string I wrote this program to check the number of times that each letter appears in a string input by the user. It works fine, but is there a more efficient or alternative solution of going about this task than reiterating through a twenty-six-element-long array for every single character?

import java.util.Scanner;
public class Letters {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        int[] f = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        System.out.println("Enter a string.");
        String k = sc.nextLine();
        String s = k.toUpperCase();
        s = s.trim();
        int l = s.length();
        System.out.println("Checking string = " + s);
        char ch;
        for (int i = 0; i &lt; l; i++) {
            ch = s.charAt(i);
            for (int j = 0; j &lt; c.length; j++) {
                if (ch == c[j]) {
                    f[j]++;
                }
            }
        }
        System.out.println("Char\tFreq");
        for (int i = 0; i &lt; c.length; i++) {
            if (f[i] != 0) {
               System.out.println(c[i] + "\t" + f[i]);
            }
        }
    }
}
Separate logical elements

It's good to separate different logical parts of a program, for example:


Parse input: a function that takes an InputStream and returns a String
Compute frequencies: a function that takes a String and returns frequencies in some form. In your current program you used an int[], it could have been a Map&lt;Character, Integer&gt;.
Print the frequencies: a function that takes the frequencies in some form, returns nothing, and prints to screen the frequencies nicely formatted.


Computing indexes of letters

If the input string contains only uppercase letters, then you can translate those letters to array indexes in the range of 0 to 25 (inclusive) like this:

int index = ch - 'A';


This eliminates the nested loop you had.
It also eliminates the need for the c array.

Initializing arrays

Instead of this:


int[] f = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};



You could write simply int[] f = new int[26];

Instead of this:


char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};



I would take a lazy approach and write char[] c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

Use better variable names

Single-letter variable names should only be used for trivial, highly transient things.
The names f and c in the program are inappropriate, and make the program more difficult to read.