链接:https://www.nowcoder.com/questionTerminal/67df1d7889cf4c529576383c2e647c48
来源:牛客网
开发一个简单错误记录功能小模块,能够记录出错的代码所在的文件名称和行号。
处理:
1.记录最多8条错误记录,对相同的错误记录(即文件名称和行号完全匹配)只记录一条,错误计数增加;(文件所在的目录不同,文件名和行号相同也要合并)
2.超过16个字符的文件名称,只记录文件的最后有效16个字符;(如果文件名不同,而只是文件名的后16个字符和行号相同,也不要合并)
3.输入的文件可能带路径,记录文件名称不能带路径
*理解:*简单来说就是给一些出错的文件名,以及文件中具体出错的行数。同一个文件同一行中如果重复出现则说明文件的此行有多个错误。我们需要对其进行计数,最后以降序输出。
需要注意的几个点:
1.对文件中的错误数排序 需要是稳定的排序
2.只记录排序前八的文件
3.件名的长度超过16个字符,则只输出后16个字符
4.输入的文件均为绝对路径
解决的思路:
选择LinkedHashMap去解决。其中key值选择:文件名 空格 行数作为key值 value值为 key值出现的次数。拿到key值的方法有很多,这里选择创立一个以“\”分割绝对路径得到的String数组。 数组的最后一个元素就是我们需要的key值。
代码部分如下:
LinkedHashMap<String,Integer> map = new LinkedHashMap<String, Integer>();
String[] Str = sc.nextLine().split("\\\\");
String totalName = Str[Str.length-1];
map.put(totalName,map.containsKey(totalName) ? map.get(totalName)+1 : 1);
在完成了数据的录入部分后,接下来进行排序。需要注意的是排序部分是放在while(scanner.hasNext())外部的
while (sc.hasNext()) {
String[] Str = sc.nextLine().split("\\\\");
String totalName = Str[Str.length-1];
map.put(totalName,map.containsKey(totalName) ? map.get(totalName)+1 : 1);
}
sc.close();
//在这里开始排序
List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
我们对hashmap的value排序用到了Collections.sort,注意一定需要重写compare方法。
下附一篇map排序相关的博文。
添加链接描述
在完成排序后我们只需要按照格式输出就好了。需要注意两个问题,一个是文件名长度超过16,另一个是只输出前8个。
因为我们的key值是:文件名 空格 行数 的格式,我们利用split()方法将key值分割。按要求输出即可。
一个需要注意的细节就是,分割后,分开输出的文件名和行数中间记得加空格。
代码如下:
for (int i = 0; i < 8; i++) {
String[] ret = list.get(i).getKey().split(" ");
if(ret[0].length() > 16) {
String r = ret[0].substring(ret[0].length()-16,ret[0].length());
System.out.println(r + " " + ret[1] + " " + list.get(i).getValue());
}else {
System.out.println(list.get(i).getKey() + " " + list.get(i).getValue());
}
}
完整代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedHashMap<String,Integer> map = new LinkedHashMap<String, Integer>();
while (sc.hasNext()) {
String[] Str = sc.nextLine().split("\\\\");
String totalName = Str[Str.length-1];
map.put(totalName,map.containsKey(totalName) ? map.get(totalName)+1 : 1);
}
sc.close();
List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
for (int i = 0; i < 8; i++) {
String[] ret = list.get(i).getKey().split(" ");
if(ret[0].length() > 16) {
String r = ret[0].substring(ret[0].length()-16,ret[0].length());
System.out.println(r + " " + ret[1] + " " + list.get(i).getValue());
}else {
System.out.println(list.get(i).getKey() + " " + list.get(i).getValue());
}
}
}
}
希望可以帮助你。