文件中查人数

某高校学生会创办了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();
			}
		}
	}

这道题,用到了 BufferedReaderHashSet 函数,通过 HashSet 查询出每组学生名单的人数,再用 if条件 进行筛选,得出结果。
注意在这之前要用到 BufferedReader 函数对文件进行读取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值