蓝桥杯兴趣小组--文件读入读出


标题:兴趣小组
为丰富同学们的业余文化生活,某高校学生会创办了3个兴趣小组
(以下称A组,B组,C组)。
每个小组的学生名单分别在【A.txt】,【B.txt】和【C.txt】中。
每个文件中存储的是学生的学号。
由于工作需要,我们现在想知道:
    既参加了A组,又参加了B组,但是没有参加C组的同学一共有多少人?
请你统计该数字并通过浏览器提交答案。
注意:答案是一个整数,不要提交任何多余的内容。
--------------------
笨笨有话说:
    哇塞!数字好多啊!一眼望过去就能发现相同的,好像没什么指望。
不过,可以排序啊,要是每个文件都是有序的,那就好多了。
歪歪有话说:
    排什么序啊,这么几行数字对计算机不是太轻松了吗?
    我看着需求怎么和中学学过的集合很像啊.....

分析:这个题很简单,就是利用文件读入读出来处理值就可以了,主要是会用文件,借这个题复习一下用法吧:

import java.io.*;
import java.util.*;
public class Main {
    static Scanner in = new Scanner(System.in);
    static String[]  solve(String path) throws IOException {//读取文件并且返回结果数组
    	String[] te = new String[500];
    	int k = 0;
    	File f = new File(path);
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
		String s;
		String[] ss;
		while((s=reader.readLine())!=null) {
			s = s.replace(" ", "");
			ss = s.split(",");
			for(int i = 0;i < ss.length;i++)
				te[k++] = ss[i];
		}
		reader.close();
		String[] res = Arrays.copyOf(te, k);
		return res;
    }
	public static void main(String[] args) throws IOException {
		String[] a ;
		String[] b ;
		String[] c ;
		String[] te = new String[500];
		int k = 0;
		int cnt1 = 0;
		String path = "C:\\Users\\JingleLi\\Desktop\\a.txt";
		a = solve(path);
		path = "C:\\Users\\JingleLi\\Desktop\\b.txt";
		b = solve(path);
		path = "C:\\Users\\JingleLi\\Desktop\\c.txt";
		c = solve(path);
		
		for(int i = 0;i < a.length;i++)
			for(int j = 0;j < b.length;j++)
				if(a[i].equals(b[j])) {
					cnt1++;//A和B组相同的
					te[k++] = b[j];
				}
		for(int i = 0;i < c.length;i++)
			for(int j = 0;j < k;j++)
				if(c[i].equals(te[j]))
					cnt1--;//减去和C组重复的
		System.out.println(cnt1);
	}
}
思考:注意文件路径


猜你喜欢

转载自blog.csdn.net/JingleLiA/article/details/79712447