我有一个进入文件的代码,它告诉用户这个词在文件中出现了多少次。如
测试.txt
Hi how are you?
good and you?
输出:
hi = 1
how = 1
are = 1
you = 2
good = 1
and = 1
我将如何添加到这个代码中,这样它也会告诉您它出现在哪一行。例子:
Hi = 1
you = 2 appeared on line 1 and 2
这是目前为止的代码。谢谢!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Text
{
public static void main(String[] args) throws FileNotFoundException {
File file = new File("Test.txt");
Scanner scan = new Scanner(file);
Map<String,Integer> map = new HashMap<String, Integer>();
while (scan.hasNextLine())
{
String val = scan.nextLine();
if(map.containsKey(val) == false)
map.put(val,1);
else
{
int count = (int)(map.get(val));
map.remove(val);
map.put(val,count+1);
}
}
Set<Map.Entry<String, Integer>> set = map.entrySet();
List<Map.Entry<String, Integer>> sortedList = new ArrayList<Map.Entry<String, Integer>>(set);
Collections.sort( sortedList, new Comparator<Map.Entry<String, Integer>>()
{
public int compare( Map.Entry<String, Integer> a, Map.Entry<String, Integer> b )
{
return (b.getValue()).compareTo( a.getValue() );
}
} );
for(Map.Entry<String, Integer> i:sortedList){
System.out.println(i.getKey()+" -> "+i.getValue()+" appears");
}
}
}
暂无答案!
目前还没有任何答案,快来回答吧!