用于计算单词输入次数的程序,然后按降序返回单词和次数

时间:2015-11-10 23:13:12

标签: java

目的是创建一个程序,该程序将计算输入单词的次数,同时忽略大小写和标点符号,然后将该单词及其输入到控制台的次数按降序返回。目前,我的程序计算字母数并将其返回到控制台,但它不会忽略大小写或标点符号。我也不确定如何添加sort函数。感谢您的时间/帮助。

编辑:不确定原始代码有什么变化,但是当我最后一次在eclipse中运行它时,计数器会忽略标点符号和大小写。但是,计数器仍在跟踪字母而不是单词。

public static void main(String[] args) {

    String txt = readText();
    String[] words = txtToWords(normalize(txt));

    HashMap<String, Integer> wordCount = countWords(words);

    //Print to console how many times each word was entered 
    System.out.println(txt + "was found" + wordCount + "times");

}
    //Increases word counter by 1 each time a duplicate word is entered
public static HashMap<String, Integer> countWords(String[] words) {
    HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
    for (String word : words) {
        if (wordCount.containsKey(word)) {
            int count = wordCount.get(word);
            count = count + 1;
            wordCount.put(word, count);
        } else {
            wordCount.put(word, 1);
        }
    }
    return wordCount;
}

public static String[] txtToWords(String txt) {
    return txt.split("");
}
    //Removes punctuation and ignores case when counting
public static String normalize(String txt) {
    txt = txt.replaceAll("[^a-zA-Z ]", "").toLowerCase();
    return txt;
}
    //Reads the text entered by the user
public static String readText() {
    System.out.println("Please enter the text to be processed.");
    String stop = "*** LAST LINE ***";
    System.out.println("Enter: \"" + stop + "\" to stop");

    StringBuilder results = new StringBuilder();
    Scanner input = new Scanner(System.in);
    while (true) {
        String line = input.nextLine();
        if (line.contains(stop)) {
            break;
        } else {
            results.append(line);
        }
    }
    return results.toString().trim();
}

}

1 个答案:

答案 0 :(得分:0)

因为你使用normalize方法在字符串中留下了空格。你应该拆分这些而不是空字符串:

str.split("\\s+");