我'm working a program that counts the accurrences of words in a text file. The program compiles and runs fine, but I' m尝试使用split方法从单词中分隔 .,;:!?(){}
等特殊字符 .
这是一个输出示例
6 eyes,
3 eyes.
2 eyes;
1 eyes?
1 eyrie
如您所见,分割功能不起作用 . 我试过调试,但到目前为止没有运气 . 任何人都可以指出我正确的方向或告诉我我做错了什么 . 谢谢 .
import java.util.*;
import java.io.*;
public class testingForLetters {
public static void main(String[] args) throws FileNotFoundException {
// open the file
Scanner console = new Scanner(System.in);
System.out.print("What is the name of the text file? ");
String fileName = console.nextLine();
Scanner input = new Scanner(new File(fileName));
// count occurrences
Map<String, Integer> wordCounts = new TreeMap<String, Integer>();
while (input.hasNext()) {
input.next().split("[ \n\t\r.,;:!?(){}]" );
String next = input.next().toLowerCase();
if (next.startsWith("a") || next.startsWith("b") || next.startsWith("c") || next.startsWith("d") || next.startsWith("e") ) {
if (!wordCounts.containsKey(next)) {
wordCounts.put(next, 1);
} else {
wordCounts.put(next, wordCounts.get(next) + 1);
}
}
}
// get cutoff and report frequencies
System.out.println("Total words = " + wordCounts.size());
for (String word : wordCounts.keySet()) {
int count = wordCounts.get(word);
System.out.println(count + "\t" + word);
}
}
}
1 回答
.split()
方法返回一个字符串数组,现在你没有设置input.next().split()
等于任何东西 . 您必须创建一个数组并将其设置为input.next().split()
,然后从数组中获取单词 . 你基本上需要像处理.toLowerCase()
部分一样处理它,就像你设置String next = input.next().toLowerCase()
一样 . 希望这可以帮助 .