WordCount getLetterCount()方法

时间:2015-11-16 22:29:31

标签: java bluej

我正在尝试填写updateLetterCount()方法的代码,该方法应该与updateDigramCount()方法非常相似。但是,我被卡住了。任何的意见都将会有帮助!我在定义字母变量时遇到了麻烦,因为我知道必须为Map定义它。关于如何去做的任何想法?

// imports of classes used for creating GUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

// imports related to reading/writing files
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

// imports of general-purpose data-structures
import java.util.TreeMap;
import java.util.Map;
import java.util.Set;

/**
 * WordCount
 * 
 * WordCount is an application for analyzing the occurrence of words, letters,
 * and letter-combinations that are found in a text block.
 * 
 * The text block can be either pasted into a window, or it can be loaded from a
 * text-file.
 * 
 */
public class WordCount extends JFrame {
    //-------------------------------------------------------------------------------------------------------

    public static final String startString = 
  "Infrequently Asked Questions\n"
+ "\n"
+ "    1. Why does my country have the right to be occupying Iraq?\n"
+ "    2. Why should my country not support an international court of justice?\n"
+ "    3. Is my country not strong enough to achieve its aims fairly?\n"
+ "    4. When the leaders of a country cause it to do terrible things, what is the best way to restore the honor of that country?\n"
+ "    5. Is it possible for potential new leaders to raise questions about their country's possible guilt, without committing political suicide?\n"
+ "    6. Do I deserve retribution from aggrieved people whose lives have been ruined by actions that my leaders have taken without my consent?\n"
+ "    7. How can I best help set in motion a process by which reparations are made to people who have been harmed by unjust deeds of my country?\n"
+ "    8. If day after day goes by with nobody discussing uncomfortable questions like these, won't the good people of my country be guilty of making things worse?\n"
+ "\n"
+ "Alas, I cannot think of a satisfactory answer to any of these questions. I believe the answer to number 6 is still no; yet I fear that a yes answer is continually becoming more and more appropriate, as month upon month goes by without any significant change to the status quo.\n"
+ "\n"
+ "Perhaps the best clues to the outlines of successful answers can be found in a wonderful speech that Richard von Weizsäcker gave in 1985:\n"
+ "\n"
+ " >    The time in which I write ... has a horribly swollen belly, it carries in its womb a national catastrophe ... Even an ignominious issue remains something other and more normal than the judgment that now hangs over us, such as once fell on Sodom and Gomorrah ... That it approaches, that it long since became inevitable: of that I cannot believe anybody still cherishes the smallest doubt. ... That it remains shrouded in silence is uncanny enough. It is already uncanny when among a great host of the blind some few who have the use of their eyes must live with sealed lips. But it becomes sheer horror, so it seems to me, when everybody knows and everybody is bound to silence, while we read the truth from each other in eyes that stare or else shun a meeting. \n"
+ " >\n"
+ " >    Germany ... today, clung round by demons, a hand over one eye, with the other staring into horrors, down she flings from despair to despair. When will she reach the bottom of the abyss? When, out of uttermost hopelessness --- a miracle beyond the power of belief --- will the light of hope dawn? A lonely man folds his hands and speaks: ``God be merciful to thy poor soul, my friend, my Fatherland!'' \n"
+ " >\n"
+ " >    -- Thomas Mann, Dr. Faustus (1947, written in 1945)\n"
+ " >          [excerpts from chapter 33 and the epilogue] \n"
+ "\n"
+ "[ Author: Donald Knuth ; Source: http://www-cs-faculty.stanford.edu/~uno/iaq.html ]\n";

    //-------------------------------------------------------------------------------------------------------

    /**
     * getDigramCount
     * 
     * Get a count of how many times each digram occurs in an input String.
     * A digram, in case you don't know, is just a pair of letters.
     * 
     * @param text a string containing the text you wish to analyze
     * @return a map containing entries whose keys are digrams, and
     *         whose values correspond to the number of times that digram occurs
     *         in the input String text.
     */
    public Map<String,Integer> getDigramCount(String text)
    { 
        Map<String,Integer> digramMap = new TreeMap<String,Integer>();

        text = text.toLowerCase();
        text = text.replaceAll("\\W|[0-9]|_","");

        for(int i=0;i<text.length()-1;i++)
        {
            String digram = text.substring(i,i+2);
            if(!digramMap.containsKey(digram))
            {
                digramMap.put(digram,1);
            } else {

                int freq = digramMap.get(digram);

                freq++;

                digramMap.put(digram,freq);
            }
        }

        return digramMap;
    }    

    /**
     * updateDigramCount
     * 
     * Use the getDigramCount method to get the digram counts from the
     * input text area, and then update the appropriate output area with
     * the information.
     */
    public void updateDigramCount()
    {
        Map<String,Integer> wordCountList = getDigramCount(words);

        StringBuffer sb = new StringBuffer();

        Set<Map.Entry<String,Integer>> values = wordCountList.entrySet();

        for(Map.Entry<String,Integer> me : values)
        {
            // We will only print the digrams that occur at least 5 times.
            if(me.getValue() >= 5) 
            {
                sb.append(me.getKey()+"  "+me.getValue()+"\n");
            }
        }
        digramCountText.setText(sb.toString());
    }

    /**
     * getLetterCount
     * 
     * Get a count of how many times each letter occurs in an input String.
     * 
     * @param text a string containing the text you wish to analyze
     * @return a map containing entries whose keys are alphabetic letters, and
     *      whose values correspond to the number of times that letter occurs
     *         in the input String text.
     */
    public Map<Character,Integer> getLetterCount(String text)
    {
        Map<Character,Integer> letterMap = new TreeMap<Character,Integer>();
    text = text.toLowerCase();
        // Now get rid of anything that is not an alphabetic character.
        text = text.replaceAll("\\W|[0-9]|_","");

        for(int i=0;i<text.length()-1;i++)
        {
            Character letter = text.charAt(i);
            if(!letterMap.containsKey(letter))
            {
                letterMap.put(letter,1);
            } else {

                int freq = letterMap.get(letter);

                freq++;

                letterMap.put(letter,freq);
            }
        }
        return new TreeMap<Character,Integer>();
    }    

    /**
     * updateLetterCount
     * 
     * Use the getLetterCount method to get the letter counts from the
     * input text area, and then update the appropriate output area with
     * the information.
     */
    public void updateLetterCount()
    {

        String words = theText.getText();

        Map<Character,Integer> letterCountList = getLetterCount(letter);

        StringBuffer sb = new StringBuffer();

        Set<Map.Entry<Character,Integer>> values = letterCountList.entrySet();

        for(Map.Entry<Character,Integer> me : values)
        {
            if(me.getValue() >= 5) 
            {
                sb.append(me.getKey()+"  "+me.getValue()+"\n");
            }
        }
        letterCountText.setText(sb.toString());
    }

This is a screenshot of the error

1 个答案:

答案 0 :(得分:1)

public Map<Character,Integer> getLetterCount(String text)
{
    ...
    return new TreeMap<Character,Integer>();
}    

返回一张空地图。您想在此处返回letterMap