public class IdiomProcessor { public static void main(String[] args) { // 定义输入文件路径和输出文件路径 String inputFile ="D:\yy\java\成语接龙\成语大全\去重后.txt"; String outputFile = "D:\yy\java\成语接龙\成语大全\全量成语处理后.txt"; try (BufferedReader reader = new BufferedReader(new FileReader(inputFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { // 定义成语列表和成语末尾字与开头字相同的数量Map List<String> idiomList = new ArrayList<>(); Map<String, Integer> countMap = new HashMap<>(); // 读取每一行成语信息 String line; while ((line = reader.readLine()) != null) { if (line.trim().isEmpty()) { continue; // 跳过空行 } if (line.contains("拼音:")) { // 处理包含指定内容的行 System.out.println("我动了"); // 将成语与其他信息分割 String[] parts = line.split("拼音:"); // 将成语加入成语列表 String idiom = parts[0]; idiomList.add(idiom); // 计算成语末尾字与开头字相同的数量 char lastChar = idiom.charAt(idiom.length() - 1); String key = lastChar + parts[1]; countMap.put(key, countMap.getOrDefault(key, 0) + 1); // 将原来的信息每一条加上count后输出到另一个文件 String newLine = line + "可接:" + countMap.get(idiom) + "\n"; writer.write(newLine); } } } catch (IOException e) { e.printStackTrace(); } } }这个代码在统计总末尾时count总是小于本该等于的值,是不是在循环内进行map添加时,受当前已经添加的成语列表限制,未扫描到的无法统计进去,怎么改善这个问题
时间: 2024-03-13 22:47:46 浏览: 18
你的猜测是正确的,因为在扫描每个成语时,只有在这个成语之前出现的成语才会被计算在内。为了解决这个问题,你可以在读取完整个文件后再次遍历成语列表,重新计算每个成语的可接数量。以下是修改后的代码:
```
public class IdiomProcessor {
public static void main(String[] args) {
// 定义输入文件路径和输出文件路径
String inputFile = "D:\\yy\\java\\成语接龙\\成语大全\\去重后.txt";
String outputFile = "D:\\yy\\java\\成语接龙\\成语大全\\全量成语处理后.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
// 定义成语列表和成语末尾字与开头字相同的数量Map
List<String> idiomList = new ArrayList<>();
Map<String, Integer> countMap = new HashMap<>();
// 读取每一行成语信息
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().isEmpty()) {
continue; // 跳过空行
}
if (line.contains("拼音:")) {
// 处理包含指定内容的行
System.out.println("我动了");
// 将成语与其他信息分割
String[] parts = line.split("拼音:");
// 将成语加入成语列表
String idiom = parts[0];
idiomList.add(idiom);
// 计算成语末尾字与开头字相同的数量
char lastChar = idiom.charAt(idiom.length() - 1);
String key = lastChar + parts[1];
countMap.put(key, countMap.getOrDefault(key, 0) + 1);
// 将原来的信息每一条加上count后输出到另一个文件
String newLine = line + "可接:" + countMap.get(idiom) + "\n";
writer.write(newLine);
}
}
// 再次遍历成语列表,重新计算每个成语的可接数量
for (String idiom : idiomList) {
char lastChar = idiom.charAt(idiom.length() - 1);
String key = lastChar + "";
int count = countMap.getOrDefault(key, 0);
countMap.put(key, count + 1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这样,每个成语的可接数量就会被正确地计算出来了。