Java实验十一 文件输入与输出

一、实验目的

  1. 掌握字符流的基本概念与用法;
  2. 掌握文件的处理方法。

实验内容:

必做

  1. 编写一个程序:要求从DOS控制台以提问对话的形式,输入三个同学的姓名、年龄、c语言成绩与java成绩,并将成绩保存到一个“chengji.txt”的文件中.
    提示:
  • 创建一个Student学生类,其中域变量包括name,age,javaScore和cScore;
  • 创建一个TestChengji类,在main主方法中创建一个学生对象数组, Student[] StudentInfo=new Student[3]
  • 将控制台输入的数据保存在数组中,然后再将数组中的成绩到一个文件中。(写入对象PrintWriter或者使用对象流)
  • 尽量使用带缓冲的数据流

实验解答

package ex11;

public class Student {
	String name;
	int age;
	double javaScore , cScore;
	
	//构造方法
	public Student(String name,int age,double javaScore,double cScore){
		this.name = name;
		this.age = age;
		this.javaScore = javaScore;
		this.cScore = cScore;
		
	}
	

}

package ex11;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestChengji {

	public static void main(String[] args) throws Exception{
		Student [] StudentInfo = new Student[3];
		
		try {
			
		
			for(int i = 0;i<StudentInfo.length;i++){
			
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			
				System.out.println("请输入第"+(i+1)+"同学的名字");
				String name = br.readLine();
				System.out.println("请输入第"+(i+1)+"位同学的年龄");
				int age = br.read();
				System.out.println("请输入第"+(i+1)+"的java成绩");
				BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
				double javaScore = br1.read();
				System.out.println("请输入第"+(i+1)+"的c语言成绩");
				BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
				double cScore = br2.read();
				StudentInfo[i] = new Student(name,age,javaScore,cScore);
			}
				
		} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		
		BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\eclipse-workspace\\41008611pengyuyan\\src\\ex11\\chengji.txt"));
		bw.write("姓名"+'\t'+"java成绩"+'\t'+"c语言成绩");
		bw.newLine();
		for(int i = 0 ;i < 3;i++) {
			String temp = Double.toString(StudentInfo[i].javaScore);
			String temp1 = Double.toString(StudentInfo[i].cScore);
			bw.write(StudentInfo[i].name+'\t'+temp+'\t'+temp1);
			bw.newLine();
			//temp += " ";
			//temp = Double.toString(StudentInfo[i].cScore);
			//bw.write(temp);
			
		}
		//bw.write(str);
		bw.close();
		System.out.println("数据输入完成!");
	}

}


实验总结:

学习了文件带缓存字节流的输入的使用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值