某高校学生会创办了3个兴趣小组(以下称A组,B组,C组)。每个小组的学生名单分别在【A.txt】,【B.txt】,【C.txt】中。每个文件中存储的是学生的学号。
由于工作需要,我们现在想知道:
既参加了A组,又参加了B组,但是没有参加C组的同学一共有多少人?
public static void main(String[] args) {
int num = 0;
Set<String> aSet = new HashSet<String>();
Set<String> bSet = new HashSet<String>();
Set<String> cSet = new HashSet<String>();
read(aSet, "C:\\Users\\Administrator\\Desktop\\蓝桥杯历年考题代码\\src\\_17\\A.txt");
read(bSet, "C:\\Users\\Administrator\\Desktop\\蓝桥杯历年考题代码\\src\\_17\\B.txt");
read(cSet, "C:\\Users\\Administrator\\Desktop\\蓝桥杯历年考题代码\\src\\_17\\C.txt");
System.out.println("A文件有:"+aSet.size());
System.out.println("B文件有:"+bSet.size());
System.out.println("C文件有:"+cSet.size());
for (String a : aSet) {
if (bSet.contains(a) && !cSet.contains(a))
num++;
}
System.out.println(num);
}
private static void read(Set<String> set, String file) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
String line = "";
while (true) {
try {
line = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (line == null)
break;
String[] split = line.split(",");// 按逗号隔开
for (String string : split) {
String trim = string.trim();// 去除空格
if (trim.length() > 0)
set.add(trim);// 加入set
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这道题应用了 HashSet 进行查找文件, BufferedReader 读取文件,最后进行计算打印输出。