A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© _J2EE_LiXiZhen 中级黑马   /  2017-11-20 22:52  /  994 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

[Java] 纯文本查看 复制代码
//请编写程序,完成键盘录入学生信息,并计算总分将学生信息与总分一同写入文本文件 
//需求:键盘录入3个学生信息(姓名,语文成绩,数学成绩) 
//  求出每个学生的总分 
//,并且将学生的信息写入Student.txt文件中 
//     要求文件中的效果下所示 
//  
//姓名   语文成绩  数学成绩  总分 
//李四    99         88      177 
//张三    20         90      112 
//王五    100       100      200   
//  
//提示 可以写一个学生类Student里面有四个属性 这样操作起来比较方便 
//分析  : 键盘录入 Scanner对象 
//        Student 类 姓名,语文成绩,数学成绩,总分 
//        写文件  输出流 字符输出流 高效字符输出流

public class MainApp {
	public static void main(String[] args) throws IOException {
		// 创建键盘录入对象
		Scanner sc = new Scanner(System.in);
		//创建存储学生对象的集合
		ArrayList<Student> list = new ArrayList<Student>();
		// for循环录入三个学生信息
		for (int i = 0; i < 3; i++) {
			// 提示输入
			System.out.println("请输入第" + (i + 1) + "个学生的姓名");
			String name = sc.next();
			System.out.println("请输入第" + (i + 1) + "个学生的语文成绩");
			int chinese = sc.nextInt();
			System.out.println("请输入第" + (i + 1) + "个学生的数学成绩");
			int math = sc.nextInt();
			//将学生信息存入集合
			list.add(new Student(name,chinese,math));
		}
		
		//创建高效字符输出流对象
		BufferedWriter bw = new BufferedWriter(new FileWriter("Student.txt"));
		//创建StringBuilder对象
		StringBuilder builder = new StringBuilder();
		builder.append("姓名").append("\t").append("语文成绩").append("\t").append("数学成绩").append("\t").append("总分");
		//首先打印第一行文字
		bw.write(builder.toString());
		//换行
		bw.newLine();
		//遍历集合打印信息
		for(Student stu : list) {
			builder = new StringBuilder();
			//用StringBuilder对象对学生信息进行拼接(两个\t为了打印的时候能对齐)
			builder.append(stu.getName()).append("\t\t").append(stu.getChinese());
			builder.append("\t").append(stu.getMath()).append("\t\t").append(stu.getSum());
			//写入文本
			bw.write(builder.toString());
			//换行
			bw.newLine();
			//刷新
			bw.flush();
		}
		//关闭流
		bw.close();
	}
}

//学生类

public class Student {
	// 姓名
	private String name;
	// 语文成绩
	private int chinese;
	// 数学成绩
	private int math;
	// 总分
	private int sum;

	// 无参构造
	public Student() {
		super();
	}

	// 带参构造/name/chinese/math
	public Student(String name, int chinese, int math) {
		super();
		this.name = name;
		this.chinese = chinese;
		this.math = math;
	}

	// get/set
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getChinese() {
		return chinese;
	}

	public void setChinese(int chinese) {
		this.chinese = chinese;
	}

	public int getMath() {
		return math;
	}

	public void setMath(int math) {
		this.math = math;
	}

	// 计算总分的方法
	public int getSum() {
		return (this.chinese + this.math);
	}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马