實驗7 流(2學時)一、實驗目的
1. 熟悉流類庫中各種常用流的使用方法。
2. 能夠使用流類實現基本的檔案讀寫。
二、實驗內容
1. 編寫程式,在控制台視窗提示輸入兩個整數,然後接收這兩個整數,並輸出它們的和。(要求:鍵盤輸入通過流封裝System.in擷取,不要使用Scanner類)
2. 設計學生類Student,屬性:編號(整型);姓名(字串),成績(整型)。編寫一個程式:要求:(1)輸入3個學生的姓名和成績,將其姓名和成績儲存到data.txt中;(2)然後從該檔案中讀取資料,求得這五個學生的平均成績。
三、實驗要求
完成程式設計並提交實驗報告。
package Sum;import java.io.*;public class Sum {public static void main(String args[]) {BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s1,s2; int num1 = 0,num2 = 0; try{ s1=br.readLine();num1=Integer.parseInt(s1);s2=br.readLine();num2=Integer.parseInt(s2);}catch (IOException e){e.printStackTrace();} System.out.println(num1+"+"+num2+"="+(num1+num2)); }}
package WriteToFile;import java.io.*;public class Student {public void input(){ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); for(int i=0;i<3;i++) { String sno = null,sdegree = null,name = null; try { System.out.println("輸入第"+(i+1)+"個學生的學號 : "); sno=br.readLine(); System.out.println("輸入第"+(i+1)+"個學生的姓名:"); name=br.readLine(); System.out.println("輸入第"+(i+1)+"個學生的成績:"); sdegree=br.readLine(); } catch (IOException e1) { e1.printStackTrace(); } try { FileWriter fw = new FileWriter("data.txt",true); BufferedWriter bw = new BufferedWriter(fw); bw.write(sno+" "+name+" "+sdegree); bw.newLine(); bw.close(); fw.close(); } catch (IOException e){ e.printStackTrace(); } }}public double average(){String str = null;double avg = 0;String[][] temp = new String[3][3];FileReader fr; try { fr = new FileReader("data.txt"); BufferedReader br = new BufferedReader(fr); for(int i =0;(str = br.readLine())!=null;i++) { temp[i] = str.split(" "); avg += Double.parseDouble(temp[i][2]); } System.out.println("3個人的平均成績為:"+avg/3); } catch (Exception e) { e.printStackTrace(); }return 0;}public static void main(String[] args)throws IOException {Student s=new Student();s.input();s.average();}}