目的是创建一个程序,该程序将计算单词的输入次数,同时忽略大小写和标点符号,然后将单词及其输入次数按降序返回到控制台。目前,我的程序统计字母数并将其返回到控制台,但它不会忽略大小写或标点符号。我也不知道如何添加排序函数。谢谢你的时间/帮助。
编辑:不确定原始代码发生了什么变化,但当我上次在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();
}
}
因为使用normalize方法在字符串中留下了空格。你应该拆分这些而不是一个空字符串:
str.split("\s+");