java制作一个代码,告诉用户文件中的每个单词出现在哪一行

sauutmhj  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(205)

我有一个进入文件的代码,它告诉用户这个词在文件中出现了多少次。如
测试.txt

  1. Hi how are you?
  2. good and you?

输出:

  1. hi = 1
  2. how = 1
  3. are = 1
  4. you = 2
  5. good = 1
  6. and = 1

我将如何添加到这个代码中,这样它也会告诉您它出现在哪一行。例子:

  1. Hi = 1
  2. you = 2 appeared on line 1 and 2

这是目前为止的代码。谢谢!

  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.*;
  4. public class Text
  5. {
  6. public static void main(String[] args) throws FileNotFoundException {
  7. File file = new File("Test.txt");
  8. Scanner scan = new Scanner(file);
  9. Map<String,Integer> map = new HashMap<String, Integer>();
  10. while (scan.hasNextLine())
  11. {
  12. String val = scan.nextLine();
  13. if(map.containsKey(val) == false)
  14. map.put(val,1);
  15. else
  16. {
  17. int count = (int)(map.get(val));
  18. map.remove(val);
  19. map.put(val,count+1);
  20. }
  21. }
  22. Set<Map.Entry<String, Integer>> set = map.entrySet();
  23. List<Map.Entry<String, Integer>> sortedList = new ArrayList<Map.Entry<String, Integer>>(set);
  24. Collections.sort( sortedList, new Comparator<Map.Entry<String, Integer>>()
  25. {
  26. public int compare( Map.Entry<String, Integer> a, Map.Entry<String, Integer> b )
  27. {
  28. return (b.getValue()).compareTo( a.getValue() );
  29. }
  30. } );
  31. for(Map.Entry<String, Integer> i:sortedList){
  32. System.out.println(i.getKey()+" -> "+i.getValue()+" appears");
  33. }
  34. }
  35. }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题