如何显示前十个常用字符

时间:2015-11-24 07:39:44

标签: java

我必须使用数组来计算字符的频率

public class abc {
    public static void main ( String[] args) {
        Scanner input = new Scanner (System.in);

        String Text;
        System.out.print("Enter a text string:");
        Text=input.nextLine();
        System.out.println("Input String:");
        System.out.println(Text);
        }
    }
}

4 个答案:

答案 0 :(得分:2)

根据你的所作所为,你有一个woking代码。主要有3个步骤:

  1. 字符数
  2. 我使用了HashMap映射字符来计算而不是数组。递增计数时,您必须首先检查角色是否已经在地图中。

    1. 以最大的数量排序
    2. 我使用具有相反顺序的SortedMap,将计数映射到具有此计数的字符列表。由于以前的地图,我填充它。 注意:这个地图可能是首先创建的,但我认为它更容易理解,并且更接近原始代码。

      1. 打印前10个频率的字母
      2. 最后,只需浏览有序地图即可显示计数最多的字母。

        希望它可以帮到你,如果你不理解某些部分,就提问。

        public static void main(final String[] args){
            final Scanner input = new Scanner(System.in);
        
            String strInText;
            // final int intLetterCount[] = new int[52];
            final Map<Character, Integer> intLetterCount = new HashMap<>();
            System.out.print("Enter a text string:");
            strInText = input.nextLine();
            strInText = strInText.trim();
            System.out.println("");
            System.out.println("Input String:");
            System.out.println("   \"" + strInText + "\"");
        
            for (int i = 0; i < strInText.length(); i++)
            {
                final char character = strInText.charAt(i);
                final int value = character;
                if ((value >= 65 && value <= 90) || (value >= 97 && value <= 122))
                {
                    // current character count
                    final Integer currentCount = intLetterCount.get(character);
        
                    // case the character was not already present : add it to the map with count 1
                    if (currentCount == null)
                    {
                        intLetterCount.put(character, 1);
                    }
                    // case the character was present. Increment count
                    else
                    {
                        intLetterCount.put(character, currentCount + 1);
                    }
                }
            }
        
            /*
             * Sort by character usage
             */
            // create sorted map (useful to sort easily) with reverse order to have biggest count first.
            final SortedMap<Integer, List<Character>> sortedMap = new TreeMap<>(Collections.reverseOrder());
        
            // for all character found, add
            for (final Map.Entry<Character, Integer> entry : intLetterCount.entrySet())
            {
                // declare current count and current char
                final int currentCount = entry.getValue();
                final Character currentChar = entry.getKey();
        
                // get actual list of characters with the current count.
                List<Character> charactersWithCount = sortedMap.get(currentCount);
        
                // if the list is null, there was no char with the current count
                if (charactersWithCount == null)
                {
                    // create list, add the current char to it, put it in map
                    charactersWithCount = new ArrayList<>();
                    charactersWithCount.add(currentChar);
                    sortedMap.put(currentCount, charactersWithCount);
                }
                // else there was other characters with the same count.
                else
                {
                    // just add the new character to the list.
                    charactersWithCount.add(currentChar);
                }
            }
        
            System.out.println("Top 10 letter counts(Number) : ");
            /*
             * print the first 10 values with higher count
             */
            final int max = 10;
            int charPrinted = 0;
            // loop through the map sorted by count
            mainLoop: for (final Map.Entry<Integer, List<Character>> entry : sortedMap.entrySet())
            {
                // loop through the list of character with the current count
                for (final Character ch : entry.getValue())
                {
                    // if we have already printed more than 10 characters, break out of the main loop.
                    if (charPrinted >= max)
                    {
                        break mainLoop;
                    }
        
                    // print char
                    System.out.println(ch + " : " + entry.getKey());
                    charPrinted++; // increase printed char count.
                }
            }
        }
        

答案 1 :(得分:0)

应该有点像这样:

System.out.println("Top 10 letter counts(Number):");
for( int i=0; i<intLetterCount.length; i++){
   char curr = 'a'+i;
   System.out.print(curr+"-"+intLetterCount[i]+",");
}

答案 2 :(得分:0)

您可以尝试将字符及其计数添加到哈希图,以便您可以像键值对一样将其打印

答案 3 :(得分:0)

您还可以使用流API:

final String input = "I am an Unicorn";
final Map<Character, Long> collect =
        input.chars( ).mapToObj( c -> (char) c )
             .collect( Collectors.groupingBy( Function.identity( ), Collectors.counting( ) ) );

collect.forEach( ( character, count ) -> System.out.println( character + "-" + count ) );

或显示前10名:

collect.entrySet( ).stream( )
       .sorted( Comparator.<Entry<Character, Long>>comparingLong( Entry::getValue ).reversed() )
       .limit( 10 )
       .forEach( ( e ) -> System.out.println( e.getKey()+ "-" + e.getValue()) );