求问Java问题,怎么在打开的文件和读取的字典里增加重复的数据,而且同时要做到插入的时候不报错!
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
// 打开文件以追加方式写入
FileWriter writer = new FileWriter("data.txt", true);
// 写入重复数据
for (int i = 0; i < 3; i++) {
writer.write("apple orange banana\n");
}
// 关闭文件写入流
writer.close();
// 打开文件
File file = new File("data.txt");
// 创建用于读取文件的Scanner对象
Scanner scanner = new Scanner(file);
// 使用HashMap作为字典数据结构
Map<String, Integer> dictionary = new HashMap<>();
// 读取文件内容并添加到字典中
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] tokens = line.split(" ");
for (String token : tokens) {
dictionary.put(token, dictionary.getOrDefault(token, 0) + 1);
}
}
// 关闭Scanner
scanner.close();
// 输出字典内容
for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
} catch (IOException e) {
System.out.println("发生IO异常!");
}
}
}
酱紫?
非要在字典中添加重复内容,可以使用字典嵌套的吧。字典的特性就是key唯一,value任意。甚至您整个字典的所有key,都可以赋同一个值。如果您说的“重复”仅是键值的话,那本就不是个事儿。如果重复的是键值对,那建议您最好换一个数据结构处理,比用字典更适宜。我认为。