改代码,上述代码统计count偏多,此外“可接:”+count要放在完整的成语信息最后
时间: 2024-03-14 16:42:58 浏览: 25
好的,以下是修改后的代码:
```java
import java.io.*;
import java.util.*;
public class IdiomCounter {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\yy\\java\\成语接龙\\成语大全\\idiom.txt"));
List<String> idiomList = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
String[] idiomArray = line.split(" ");
idiomList.addAll(Arrays.asList(idiomArray));
}
br.close();
Map<Character, List<String>> idiomMap = new HashMap<>();
for (String idiom : idiomList) {
if (!idiom.isEmpty()) {
char lastChar = idiom.charAt(idiom.length() - 1);
List<String> idiomSet = idiomMap.getOrDefault(lastChar, new ArrayList<>());
idiomSet.addAll(Collections.singleton(idiom));
idiomMap.put(lastChar, idiomSet);
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\yy\\java\\成语接龙\\成语大全\\全量成语处理后.txt"));
for (String idiom : idiomList) {
if (!idiom.isEmpty()) {
char lastChar = idiom.charAt(idiom.length() - 1);
List<String> idiomSet = idiomMap.get(lastChar);
int count = idiomSet != null ? idiomSet.size() : 0;
bw.write(idiom + " 可接:" + count);
bw.newLine();
}
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个修改后的代码中,我们将统计可接成语数量的部分移至文件写入逻辑之前,这样就不会导致统计 count 偏多的问题了。同时,我们也将“可接:”和 count 放在了完整的成语信息之后,更符合阅读习惯。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)