1

I want to write a program that takes a string text, counts the appearances of every letter in English and stores them inside an array.and print the result like this:

java test abaacc
a:***
b:*
c:**

* - As many time the letter appears.

public static void main (String[] args)  {
   String input = args[0];
   char [] letters = input.toCharArray();
   System.out.println((char)97);
   String a = "a:";
   for (int i=0; i<letters.length; i++) {
      int temp = letters[i];
      i = i+97;
      if (temp == (char)i) {
         temp = temp + "*";
      }
      i = i - 97;
   }
   System.out.println(temp);
}
2
  • 1
    So make an array of size how many letter in alphabet (26?) and then increment that index by 1 every time such a letter appears Commented Nov 13, 2015 at 21:56
  • is it case sensitive, e.g. count 'A' and 'a' separately? As @3kings said, you can have an array, indexed by the letter's position in the array. You can quickly compute this index by subtracting the ascii values, e.g. 'g' - 'a' will give you 6. If case insensitive, you will need to convert to lower case, or if letter is uppercase, subtract 'A' from it. If case sensitive, you will need an array twice as big, and figure out where to put them. Commented Nov 13, 2015 at 22:11

1 Answer 1

2

Writing (char)97 makes the code less readable. Use 'a'.

As 3kings said in a comment, you need an array of 26 counters, one for each letter of the English alphabet.

Your code should also handle both uppercase and lowercase letters.

private static void printLetterCounts(String text) {
    int[] letterCount = new int[26];
    for (char c : text.toCharArray())
        if (c >= 'a' && c <= 'z')
            letterCount[c - 'a']++;
        else if (c >= 'A' && c <= 'Z')
            letterCount[c - 'A']++;
    for (int i = 0; i < 26; i++)
        if (letterCount[i] > 0) {
            char[] stars = new char[letterCount[i]];
            Arrays.fill(stars, '*');
            System.out.println((char)('a' + i) + ":" + new String(stars));
        }
}

Test

printLetterCounts("abaacc");
System.out.println();
printLetterCounts("This is a test of the letter counting logic");

Output

a:***
b:*
c:**

a:*
c:**
e:****
f:*
g:**
h:**
i:****
l:**
n:**
o:***
r:*
s:***
t:*******
u:*
Sign up to request clarification or add additional context in comments.

1 Comment

@Dana You have to import java.util.Arrays. If you're using an IDE, it should have told you that. If you're not using an IDE, then get one now, e.g. Eclipse, NetBeans, ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.