Java實驗7 流

來源:互聯網
上載者:User
實驗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();}}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.