Java 读一个文件并对单词进行排序
我正在执行这部分代码:Java 读一个文件并对单词进行排序,java,file,sorting,Java,File,Sorting,我正在执行这部分代码: Map<String, Integer> wordMap = new HashMap<>(); File file = new File("words.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String word = scanner.nextLine();
Map<String, Integer> wordMap = new HashMap<>();
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
int count = 1;
if (wordMap.containsKey(word)) {
count = wordMap.get(word).intValue();
count++;
wordMap.remove(word);
wordMap.put(word, count);
} else {
wordMap.put(word, count);
}
System.out.println(wordMap);
代码中有什么错误???
谢谢
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
TreeMap
而不是HashMap
。树形图按顺序自动排序键李>
HashMap.toString()
。相反,请尝试以下方法:
for (String key : wordMap.keys()) {
System.out.println(key + ": " + wordMap.get(key));
}
问题是,我使用TextEditor创建文档,它创建.rtf文档。 我将其转换为.txt,但它可能已损坏它 我创建了不同的.txt文件,它成功了
Map<String, Integer> wordMap = new TreeMap<>();
File file = new File("wordCount.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
int count = 1;
if (wordMap.containsKey(word)) {
count = wordMap.get(word).intValue();
count++;
wordMap.remove(word);
wordMap.put(word, count);
} else {
wordMap.put(word, count);
}
}
System.out.println(wordMap);
scanner.close();
Map wordMap=newtreemap();
File File=新文件(“wordCount.txt”);
扫描仪=新扫描仪(文件);
while(scanner.hasNextLine()){
字符串字=scanner.nextLine();
整数计数=1;
if(wordMap.containsKey(word)){
count=wordMap.get(word.intValue();
计数++;
删除(word);
放置(单词,计数);
}否则{
放置(单词,计数);
}
}
System.out.println(wordMap);
scanner.close();
您能告诉我您的文件是什么样子的吗?你把这些词分类是什么意思?你只是想计算所有单词的频率吗?谢谢Dmitry,我现在正在使用TreeMap。这很简单。
Map<String, Integer> wordMap = new TreeMap<>();
File file = new File("wordCount.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
int count = 1;
if (wordMap.containsKey(word)) {
count = wordMap.get(word).intValue();
count++;
wordMap.remove(word);
wordMap.put(word, count);
} else {
wordMap.put(word, count);
}
}
System.out.println(wordMap);
scanner.close();