0

我不确定如何计算每个字母的出现次数。有人可以指出我这样做的正确方向吗,谢谢:)

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.
                }


         }
4

1 回答 1

1

使用Map<Character, Integer>, 并遍历字符串。在字符第一次出现时,将字符和 1 放入地图中。在所有后续出现的情况下,将地图中已存在的该字符的值加一。

然后,地图的条目集将为您提供所需的数据。

于 2013-03-07T16:59:12.850 回答