某高校学生会创办了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, "D:\\text\\A.txt");
read(bSet, "D:\\text\\B.txt");
read(cSet, "D:\\text\\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();
}
}
}
这道题,用到了 BufferedReader 、 HashSet 函数,通过 HashSet 查询出每组学生名单的人数,再用 if条件 进行筛选,得出结果。
注意在这之前要用到 BufferedReader 函数对文件进行读取。