【发布时间】:2023-03-22 15:45:01
【问题描述】:
我正在尝试读取文件中每个单词的出现次数,并将其存储在带有出现次数的哈希图中。这是我的代码。
public static void main(String[] args) {
try {
HashMap<String, Integer> map = sortingFromAFile("file.txt");
printMap(map);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static HashMap sortingFromAFile(String fileName) throws FileNotFoundException {
HashMap<String, Integer> map = new HashMap<String, Integer>();
Integer count = 1;
File file = new File(fileName);
Scanner sc = null;
try {
sc = new Scanner(file);
while(sc.hasNextLine()){
String line = sc.nextLine();
if (map.containsKey(line)){
map.put(line, count++);
}
map.put(line, count);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return map;
}
public static void printMap(HashMap map){
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + ":" + pairs.getValue() );
}
}
程序只是运行以打印出文件中的文本。我在这里做错了什么。
【问题讨论】:
-
扫描器类对每个单词进行标记,因此 nextLine( ) 表示由空格分隔的下一个字符串。
-
不,
nextLine()将光标移到下一行。你的意思可能是next()