import java.io.*;import java.util.*;public class Main { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("idiom.txt")); List<String> idiomList = new ArrayList<>(); Map<Character, List<String>> idiomMap = new HashMap<>(); String line; while ((line = br.readLine()) != null) { String[] parts = line.split(" "); String idiom = parts[0]; idiomList.add(idiom); char lastChar = idiom.charAt(idiom.length() - 1); if (!idiomMap.containsKey(lastChar)) { idiomMap.put(lastChar, new ArrayList<>()); } idiomMap.get(lastChar).add(idiom); } br.close(); BufferedWriter bw = new BufferedWriter(new FileWriter("idiom_result.txt")); br = new BufferedReader(new FileReader("idiom.txt")); while ((line = br.readLine()) != null) { String[] parts = line.split(" "); String idiom = parts[0]; char lastChar = idiom.charAt(idiom.length() - 1); int count = idiomMap.containsKey(lastChar) ? idiomMap.get(lastChar).size() : 0; bw.write(line + " " + count); bw.newLine(); } bw.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } }}这个代码在统计总末尾时count总是小于本该等于的值,是不是在循环内进行map添加时,受当前已经添加的成语列表限制,未扫描到的无法统计进去,怎么改善这个问题
时间: 2024-02-14 22:12:13 浏览: 280
你的猜测是正确的。在循环内进行map添加时,已经添加的成语列表限制了后面未扫描到的成语,导致count总是小于本该等于的值。
要改善这个问题,可以将循环分为两部分,先遍历一遍成语列表,将所有成语的结尾字符和该结尾字符对应的成语列表存储在一个Map中,然后再遍历一遍成语列表,统计每个成语结尾字符对应的成语数量。这样就不会因为未扫描到的成语而导致统计错误了。
修改后的代码如下:
```
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("idiom.txt"));
List<String> idiomList = new ArrayList<>();
Map<Character, List<String>> idiomMap = new HashMap<>();
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
String idiom = parts[0];
idiomList.add(idiom);
char lastChar = idiom.charAt(idiom.length() - 1);
if (!idiomMap.containsKey(lastChar)) {
idiomMap.put(lastChar, new ArrayList<>());
}
idiomMap.get(lastChar).add(idiom);
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("idiom_result.txt"));
for (String idiom : idiomList) {
char lastChar = idiom.charAt(idiom.length() - 1);
int count = idiomMap.containsKey(lastChar) ? idiomMap.get(lastChar).size() : 0;
bw.write(idiom + " " + count);
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文