![JAVA實驗5 流_第1頁](http://file3.renrendoc.com/fileroot_temp3/2022-2/20/38cc69b9-d507-4e95-b2a8-fcbc051afe97/38cc69b9-d507-4e95-b2a8-fcbc051afe971.gif)
![JAVA實驗5 流_第2頁](http://file3.renrendoc.com/fileroot_temp3/2022-2/20/38cc69b9-d507-4e95-b2a8-fcbc051afe97/38cc69b9-d507-4e95-b2a8-fcbc051afe972.gif)
![JAVA實驗5 流_第3頁](http://file3.renrendoc.com/fileroot_temp3/2022-2/20/38cc69b9-d507-4e95-b2a8-fcbc051afe97/38cc69b9-d507-4e95-b2a8-fcbc051afe973.gif)
![JAVA實驗5 流_第4頁](http://file3.renrendoc.com/fileroot_temp3/2022-2/20/38cc69b9-d507-4e95-b2a8-fcbc051afe97/38cc69b9-d507-4e95-b2a8-fcbc051afe974.gif)
![JAVA實驗5 流_第5頁](http://file3.renrendoc.com/fileroot_temp3/2022-2/20/38cc69b9-d507-4e95-b2a8-fcbc051afe97/38cc69b9-d507-4e95-b2a8-fcbc051afe975.gif)
版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、實驗5 流1. 編寫程序,要求:用戶在鍵盤每輸入一行文本,程序?qū)⑦@段文本顯示在控制臺中。當用戶輸入的一行文本是“exit”(不區(qū)分大小寫)時,程序?qū)⒂脩羲休斎氲奈谋径紝懭氲轿募og.txt中,并退出。(要求:控制臺輸入通過流封裝System.in獲取,不要使用Scanner)package shiyanwu1;import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; public class test1 / 獲得系統(tǒng)換行符 private static final
2、 String LINE_SEP = System.getProperty("line.separator"); public static void main(String args) throws Exception try (BufferedReader in = new BufferedReader( new InputStreamReader(System.in) String line; StringBuilder sBuilder = new StringBuilder(); while (true) line = in.readLine(); / 讀入一行字
3、符串 if (line = null | "exit".equals(line)|"EXIT".equals(line) break; sBuilder.append(line).append(LINE_SEP); / 將 sBuilder 中的數(shù)據(jù)寫入 log.txt try (PrintWriter writer = new PrintWriter("D:/java examples/my java/src/shiyanwu1/show.txt") writer.print(sBuilder.toString(); 2. 查看Fi
4、le類的API文檔,使用該類實現(xiàn)一個類FileList,它提供兩個靜態(tài)方法:1)printContentsInOneDirectory:能夠?qū)⑤斎雲(yún)?shù)path所指定的本地磁盤路徑下的所有目錄和文件的名稱(指明是目錄還是文件,格式見下圖)打印出來;2)readFileAndDirectory:能夠?qū)⑤斎雲(yún)?shù)path所指定的本地磁盤路徑下的所有目錄(包含子目錄)和文件的名稱(指明是目錄還是文件,格式見下圖)以層次化結構打印出來。例如,某個目錄下面有子目錄a和文件Teacher.class,目錄a下面有子目錄b(下面有文件Teacher.java)和c(下面有文件Test.java和Test.cla
5、ss)以及文件1.txt,將該目錄對應的路徑作為輸入?yún)?shù)調(diào)用該方法,程序的輸出如下圖所示。package shiyanwu2;import java.io.File; public class test2 Public static void printContentsInOneDirectory(String path) File file = new File(path); if (!file.exists() throw new RuntimeException(String.format("文件 %s 不存在!", path); File childFiles =
6、file.listFiles(); for (File childFile : childFiles) if (childFile.isFile() System.out.format("文件 %sn", childFile.getName(); else System.out.format("目錄 %sn", childFile.getName(); /* * * param path 目錄路徑 * param indent 當前縮進(即輸出 - ) 的個數(shù) */ public static void readFileAndDirectory(Stri
7、ng path, int indent) File file = new File(path); if (!file.exists() throw new RuntimeException(String.format("文件 %s 不存在!", path); File childFiles = file.listFiles(); for (File childFile : childFiles) for (int i = 0; i < indent; +i) System.out.print("-"); if (childFile.isFile()
8、 System.out.format("文件 %sn", childFile.getName(); else System.out.format("目錄 %sn", childFile.getName(); readFileAndDirectory(childFile.getAbsolutePath(), indent + 2); public static void main(String args) throws Exception System.out.println("測試 printContentsInOneDirectory 方法:
9、"); printContentsInOneDirectory("some_dir"); System.out.println("n測試 readFileAndDirectory 方法:"); readFileAndDirectory("some_dir", 0); 3. 假設某個餐館平時使用:1)文本文件(orders.txt)記錄顧客的點菜信息,每桌顧客的點菜記錄占一行。每行顧客點菜信息的記錄格式是“菜名:數(shù)量,菜名:數(shù)量,菜名:數(shù)量”。例如:“烤鴨:1,土豆絲:2,烤魚:1”。2)文本文件(dishes.txt)記錄每
10、種菜的具體價格,每種菜及其價格占一行,記錄格式為“菜名:價格“。例如:“烤鴨:169”。編寫一個程序,能夠計算出orders.txt中所有顧客消費的總價格。package shiyanwu3;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java
11、.util.List;import java.util.Map;public class order public static void main(String args) order first = new order();List<String> orderDatas = first.readFile("D:/java examples/my java/src/shiyanwu3/orders.txt");List<String> dishesDatas = first.readFile("D:/java examples/my ja
12、va/src/shiyanwu3/dishes.txt");Map<String, Integer> orderDetail = first.resolveOrderDatas(orderDatas);Map<String, Integer> dishesDetail = firs.resolveOrderDatas(dishesDatas);String dishesName = null;int dishesCount = 0;int totalPrice = 0;for (Map.Entry<String, Integer> e : orde
13、rDetail.entrySet() dishesName = e.getKey();dishesCount = e.getValue();totalPrice += dishesDetail.get(dishesName) * dishesCount;System.err.println(dishesName+"總消費為:"+totalPrice);private List<String> readFile(String fileName) if (fileName != null && !"".equals(fileNam
14、e) File file = null;file = new File(fileName);if (file.exists() List<String> datas = new ArrayList<String>();try InputStream is = new FileInputStream(file);BufferedReader br = new BufferedReader(new InputStreamReader(is,"gb2312");String str = null;while (true) str = br.readLine
15、();if (str != null) datas.add(str); else break;br.close(); catch (Exception e) return datas;return null;private Map<String, Integer> resolveOrderDatas(List<String> datas) String temp1 = null, temp2 = null;String detailStr = null;Map<String, Integer> orderDetail = new HashMap<>
16、;();for (int i = 0; i < datas.size(); i+) temp1 = datas.get(i).split(",");for (int j = 0; j < temp1.length; j+) temp2 = temp1j.split(":");if (temp2.length = 2) if (orderDetail.get(temp20) != null) orderDetail.put(temp20, Integer.parseInt(temp21)+ orderDetail.get(temp20); el
17、se orderDetail.put(temp20, Integer.parseInt(temp21);return orderDetail;private Map<String, Integer> resolveDishesDatas(List<String> datas) Map<String, Integer> dishesDetail = new HashMap<>();String temp = null;for (int i = 0; i < datas.size(); i+) temp = datas.get(i).split
18、(":");if (temp.length = 2) dishesDetail.put(temp0, Integer.parseInt(temp1);return dishesDetail;4. 設計學生類Student,屬性:學號(整型);姓名(字符串),選修課程(名稱)及課程成績(整型)。編寫一個控制臺程序,能夠?qū)崿F(xiàn)Student信息的保存、讀取。具體要求:(1)提供Student信息的保存功能:通過控制臺輸入若干個學生的學號、姓名以及每個學生所修課程的課程名和成績,將其信息保存到data.dat中;(2)數(shù)據(jù)讀取顯示:能夠從data.dat文件中讀取學生及其課程成績并
19、顯示于控制臺。package shiyanwu4;public class Student private int number;private String name;private String courseName;private int score;public int getNumber() return number;public void setNumber(int number) this.number = number;public String getName() return name;public void setName(String name)
20、= name;public String getCourseName() return courseName;public void setCourseName(String courseName) this.courseName = courseName;public int getScore() return score;public void setScore(int score) this.score = score;package shiyanwu4;import java.io.BufferedReader;import java.io.BufferedWriter;import
21、java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class StudentMgr public static final String studentDat = "
22、;E:/data.dat"public static void main(String args) showMenu();Scanner s = null;s = new Scanner(System.in);String code = null;Student student;List<Student> datas = new ArrayList<Student>();List<Student> savedStudents = readStudentDat(studentDat);while (true) code = s.next();if (
23、"#4".equalsIgnoreCase(code) System.err.println("程序已退出");break; else if ("#1".equalsIgnoreCase(code) String tmpStr = null;int tmpInt;while (true) System.out.print("學生學號:");tmpInt = s.nextInt();student = new Student();student.setNumber(tmpInt);System.out.print(&
24、quot;學生姓名:");tmpStr = s.next();student.setName(tmpStr);System.out.print("學生課程:");tmpStr = s.next();student.setCourseName(tmpStr);System.out.print("課程成績:");tmpInt = s.nextInt();student.setScore(tmpInt);datas.add(student);System.out.println("輸入exit結束信息錄入,輸入其他繼續(xù)錄入");t
25、mpStr = s.next();if ("exit".equalsIgnoreCase(tmpStr) break;if ("exit".equalsIgnoreCase(tmpStr) showMenu();continue; else if ("#3".equalsIgnoreCase(code) try if(datas.size() >0 )saveStudents(datas);elseSystem.err.println("無可保存的學生信息"); catch (IOException e) S
26、ystem.err.println("保存學生信息異常");e.printStackTrace();else if ("#2".equalsIgnoreCase(code) List<Student> students = readStudentDat(studentDat);if(students = null | students.size() = 0)System.err.println("暫無學生信息");showMenu();elseSystem.err.println("已有學生人數(shù):"+s
27、tudents.size();for(int i=0;i<students.size();i+)/這里輸出學生信息elseSystem.err.println("無法識別的菜單");showMenu();public static List<Student> readStudentDat(String fileName) if (fileName != null && !"".equals(fileName) File file = null;file = new File(fileName);Student stude
28、nt = null;if (file.exists() List<Student> datas = new ArrayList<Student>();try InputStream is = new FileInputStream(file);BufferedReader br = new BufferedReader(new InputStreamReader(is, "gb2312");String str = null;String infos = null;while (true) str = br.readLine();if (str !=
29、 null) student = new Student();str = br.readLine();infos = str.split("#");student.setNumber(Integer.parseInt(infos0);student.setName(infos1);student.setCourseName(infos2);student.setScore(Integer.parseInt(infos3);datas.add(student); else break;br.close(); catch (Exception e) e.printStackTr
30、ace();return datas;return null;public static void saveStudents(List<Student> students) throws IOException File file = new File(studentDat);if (!file.exists() file.createNewFile();BufferedWriter bw = new BufferedWriter(new FileWriter(file,true);StringBuffer sb = new StringBuffer();Student s = n
31、ull;for (int i = 0; i < students.size(); i+) s = students.get(i);sb.setLength(0);sb.append(s.getNumber() + "#" + s.getName() + "#"+ s.getCourseName() + "#" + s.getScore();bw.write(sb.toString();bw.write("n");bw.flush();bw.close();public static void showMenu
32、() System.out.println("-");System.out.println("-#1、錄入學生信息-");System.out.println("-#2、查看學生信息-");System.out.println("-#3、保存學生信息-");System.out.println("-#4、退出-");System.out.println("-");5. 編寫程序,在控制臺窗口提示輸入兩個整數(shù),然后接收這兩個整數(shù),并輸出它們的和。(要求:鍵盤輸入通過
33、流封裝System.in獲取,不要使用Scanner類)InputStreamTest.javapackage com.ly.stream;import java.io.BufferedReader;import java.io.InputStreamReader;public class InputStreamTest public static void main(String args) BufferedReader in = new BufferedReader(new InputStreamReader(System.in); String line=null; try System
34、.out.print("請輸入第一個正整數(shù)a:"); line = in.readLine(); int a = Integer.parseInt(line); System.out.print("請輸入第二個正整數(shù)b:"); line = in.readLine(); int b = Integer.parseInt(line); System.out.println("a+b=" + String.valueOf(a+b); catch(Exception e) System.out.println("輸入錯誤!&quo
35、t;); System.exit(0); 6.設計學生類Student,屬性:編號(整型);姓名(字符串),成績(整型)。編寫一個程序:要求:(1)輸入3個學生的姓名和成績,將其姓名和成績保存到data.txt中;(2)然后從該文件中讀取數(shù)據(jù),求得這五個學生的平均成績。Student.javapackage com.ly.file;public class Student int id; String name; int score; Student() public void setId(int id) this.id = id; public void setName(String nam
36、e) = name; public void setScore(int score) this.score = score; public String toString() return this.id + "t" + + "t" + this.score + "n" Main.javapackage com.ly.file;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;impo
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年聚酯成型網(wǎng)項目可行性研究報告
- 成都四川成都簡陽市三星鎮(zhèn)便民服務和智慧蓉城運行中心招聘綜治巡防隊員筆試歷年參考題庫附帶答案詳解
- 2025年牛仔布駁掌手套項目可行性研究報告
- 2025年民用灶項目可行性研究報告
- 2025至2031年中國心可舒中藥行業(yè)投資前景及策略咨詢研究報告
- 恩施2025年湖北恩施州巴東縣教育局所屬事業(yè)單位選調(diào)6人筆試歷年參考題庫附帶答案詳解
- 2025至2031年中國壓電式渦街流量計行業(yè)投資前景及策略咨詢研究報告
- 2025年醫(yī)用消毒液項目可行性研究報告
- 2025至2030年中國黑棕2色系圍巾坐猴數(shù)據(jù)監(jiān)測研究報告
- 2025至2030年中國高發(fā)撥叉數(shù)據(jù)監(jiān)測研究報告
- 化工過程安全管理導則安全儀表管理課件
- 企業(yè)對外溝通與形象塑造制度
- 中國高血壓防治指南-解讀全篇
- 2024年監(jiān)控安裝合同范文6篇
- 2024年山東省高考政治試卷真題(含答案逐題解析)
- 煙葉復烤能源管理
- 應收賬款管理
- 食品安全管理員考試題庫298題(含標準答案)
- 非ST段抬高型急性冠脈綜合征診斷和治療指南(2024)解讀
- 2024年山東濟寧初中學業(yè)水平考試地理試卷真題(含答案詳解)
- 撫恤金喪葬費協(xié)議書模板
評論
0/150
提交評論