【发布时间】:2016-03-23 19:42:06
【问题描述】:
我需要统计txt文件中相同字符串的出现次数。
我想出的是
public class CountWords {
public File file;
public Scanner scan = null;
public LinkedHashMap<String, Integer> list = new LinkedHashMap<>();
public CountWords(String txt) {
file = new File(txt);
}
public void textEdit() {
try {
scan = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("----");
}
while (scan.hasNextLine()) {
String line = scan.nextLine();
if(!list.containsKey(line))
list.put(scan.next(),1);
else {
list.put(line,list.get(line)+1);
}
}
scan.close();
}
public List<String> getResult(){
textEdit();
return list;
}
不应以任何方式更改 Main 类(这是要求) 并且输出的顺序应该与输入的顺序相同(这就是使用 LinkedHashMap 的原因)
public class Main {
public static void main(String[] args) throws Exception {
String fname = System.getProperty("user.home") + "/textforwords.txt";
CountWords cw = new CountWords(fname);
List<String> result = cw.getResult();
for (String wordRes : result) {
System.out.println(wordRes);
}
}
}
我错过了一些我无法弄清楚的东西。
【问题讨论】:
-
这可以编译吗? getResult 被声明为返回一个列表,但您返回的是一个 LinkedHashMap。
-
@JimmyJames 不,这是我感到困惑的地方,我需要以某种方式连接这两件事,因为要求是“不要更改 Main”和“使用 LinkedHashMap”
-
getResult()返回的列表应该包含什么样的字符串?你有这方面的规范吗?
标签: java hashmap linkedhashmap