Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
790 views
in Technique[技术] by (71.8m points)

arrays - Count letters in a string Java

I'm doing an assignment where I'll have to code a program to read in a string from user and print out the letters in the string with number of occurrences. E.g. "Hello world" in which it should print out "h=1 e=1 l=3 o=2 ... etc.", but mine only write "hello world" and the amount of letters in total. I can't use the hashmap function, only arrays. Can someone give me a hint or two on how to proceed from the written code below to get my preferred function? I don't understand exactly how to save the written input in array.

Here's my code so far.

public class CountLetters {
    public static void main( String[] args ) {
        String input = JOptionPane.showInputDialog("Write a sentence." );
        int amount = 0;
        String output = "Amount of letters:
";

        for ( int i = 0; i < input.length(); i++ ) {
            char letter = input.charAt(i);
            amount++;
            output = input;
        }
        output += "
" + amount;
        JOptionPane.showMessageDialog( null, output,
                             "Letters", JOptionPane.PLAIN_MESSAGE ); 
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need 26 switch cases. Just use simple code to count letter:

    String input = userInput.toLowerCase();// Make your input toLowerCase.
    int[] alphabetArray = new int[26];
    for ( int i = 0; i < input.length(); i++ ) {
         char ch=  input.charAt(i);
         int value = (int) ch;
         if (value >= 97 && value <= 122){
         alphabetArray[ch-'a']++;
        }
    }

After done count operation, than show your result as:

 for (int i = 0; i < alphabetArray.length; i++) {
      if(alphabetArray[i]>0){
        char ch = (char) (i+97);
        System.out.println(ch +"  : "+alphabetArray[i]);   //Show the result.
      }         
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...