0

I'm not really sure how I would approach counting the occurrences of each letter. Could someone point me to the right direction in doing this, thank you :)

if(icanreadstrings.equals ("start")){ 

            String strten = Console.readLine("Enter 10 letters (no spaces,commas between each letter and no numbers): "); // Asks the user to enter 10 letters which is then saved as a string "strten".
            Console.println(strten);// Prints out whatever the user entered.

            if(strten.matches("[a-zA-Z]+") && strten.length() == 10){ // if whatever the user enters is letters (not numbers) and if it matches to the length, which is 10.
                Console.println("There are " + strten.length() + " letters that you've wrote."); // lets the user continue if they've wrote 10 letters, yes 10!

            }else{
                Console.println("There are more than or less than 10 letters that you've wrote or you have numbers in your list of letters. Please rewrite 10 different LETTERS for this program to continue."); // Checks to see if you wrote more than  10 letters if you did then it prompts a message and the user can't continue until he writes 10 letters.
                }


         }
  • 2
    *"Could someone point me to the right direction"* 1) [`String`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) 2) [Language basics](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html) -- For more specific help, ask a more specific question. – Andrew Thompson Mar 07 '13 at 16:58
  • 1
    http://stackoverflow.com/questions/275944/how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string?rq=1 – Danny Mar 07 '13 at 16:58
  • 1
    It's been asked many times - there is a search box at the top right of this page. Search for example: `[java] count occurence character string` – assylias Mar 07 '13 at 17:00
  • The right direction would be to search before asking someone to do it for you. – Brian Roach Mar 07 '13 at 17:01
  • @assylias I've searched and looked through many pages, unfortunately when I tried their code out it did not work :( – user1910660 Mar 07 '13 at 17:02

1 Answers1

1

Use a Map<Character, Integer>, and loop through the string. On the first occurrence of the character, put the character and 1 in the map. On all subsequent occurrence, add one to the value for that character already in the map.

The entry set of the map will then give you the data you're after.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216