達拉草201771010105《面向物件程式設計(java)》第十一週學習總結
達拉草201771010105《面向物件程式設計(java)》第十一週學習總結
實驗十一 集合
實驗時間 2018-11-8
第一部分:理論知識
1.集合(Collection或稱為容器)是一種包含多個元素 並提供對所包含元素操作方法的類,其包含的元 素可以由同一型別的物件組成,也可以由不同類 型的物件組成。
2.集合框架:JAVA集合類庫的統一架構。
集合類的作用: –Java的集合類提供了一些基本資料結構的支援。 例如Vector、Hashtable、Stack等。
集合類的使用: –Java的集合類包含在java.util包中。
集合類的特點:
特點一: 只容納物件。 注意:陣列可以容納基本資料型別資料和物件。 –如果集合類中想使用基本資料型別,又想利用 集合類的靈活性,可以把基本資料型別資料封 裝成該資料型別的包裝器物件,然後放入集合 中處理。
特點二: 集合類容納的物件都是Object類的例項,一旦 把一個物件置入集合類中,它的類資訊將丟失 ,這樣設計的目的是為了集合類的通用性。 因為Object類是所有類的祖先,所以可以在這 些集合中存放任何類的物件而不受限制,但切 記在使用集合成員之前必須對它重新造型。
Vector類:
Vector類類似長度可變的陣列。
Vector中只能存放物件。
Vector的元素通過下標進行訪問。
Vector類關鍵屬性: capacity表示集合多能容納的元素個數。 capacityIncrement表示每次增加多少容量。 size表示集合當前元素個數。
Stack類:Stack類是Vector的子類。
Hashtable類:
Hashtable通過鍵來查詢元素。
Hashtable用雜湊碼(hashcode)來確定鍵。所 有物件都有一個雜湊碼,可以通過Object類的 hashCode()方法獲得。
Math.random()方法的隨機性。在理想 情況下,該方法應該產生一系列完美的隨機分佈的 數字。為了驗證這一點,需要生成數量眾多的隨機 數字,然後計算落在不同範圍內的數字量。該程式 生成10000個隨機數,檢視它們在0~20之間的分 布如何。 Math.random()
返回帶正號的double值,大於或等於0.0,小於1.0。
集合框架中的基本介面
Collection:集合層次中的根介面,JDK未提供這個 介面的直接實現類。
Set:不能包含重複的元素。物件可能不是按存放的 次序存放,也就是說不能像陣列一樣按索引的方式進 行訪問,SortedSet是一個按照升序排列元素的Set。
List:是一個有序的集合,可以包含重複的元素。提 供了按索引訪問的方式。 Map:包含了key-value對。Map不能包含重複的key 。
SortedMap是一個按照升序排列key的Map。
List:
List的明顯特徵是它的元素 都有一個確定的順序。
實現它的類有ArrayList和 LinkedList。 –ArrayList中的元素在記憶體中 是順序儲存的。
LinkedList中的元素在記憶體 中是以連結串列方式儲存的。 List的明顯特徵是它的元素 都有一個確定的順序。
實現它的類有ArrayList和 LinkedList。
ArrayList中的元素在記憶體中 是順序儲存的。
LinkedList中的元素在記憶體 中是以連結串列方式儲存的。
Map接:
Map介面的實現類主要有HashMap, TreeMap,Hashtable,Properties。
Hashtable,Properties是JDK1.0/1.1中的。 HashMap對key進行雜湊。
TreeMap按照key進行排序。
和Set類似,HashMap的速度通常都比 TreeMap快,只有在需要排序的功能的時候 ,才使用TreeMap。
第二部分:實驗部分
1、實驗目的與要求
(1) 掌握Vetor、Stack、Hashtable三個類的用途及常用API;
(2) 瞭解java集合框架體系組成;
(3) 掌握ArrayList、LinkList兩個類的用途及常用API。
(4) 瞭解HashSet類、TreeSet類的用途及常用API。
(5)瞭解HashMap、TreeMap兩個類的用途及常用API;
(6) 結對程式設計(Pair programming)練習,體驗程式開發中的兩人合作。
2、實驗內容和步驟
實驗1: 匯入第9章示例程式,測試程式並進行程式碼註釋。
測試程式1:
l 使用JDK命令執行編輯、執行以下三個示例程式,結合執行結果理解程式;
l 掌握Vetor、Stack、Hashtable三個類的用途及常用API。
//示例程式1 import java.util.Vector;
class Cat { private int catNumber;
Cat(int i) { catNumber = i; }
void print() { System.out.println("Cat #" + catNumber); } }
class Dog { private int dogNumber;
Dog(int i) { dogNumber = i; }
void print() { System.out.println("Dog #" + dogNumber); } }
public class CatsAndDogs { public static void main(String[] args) { Vector cats = new Vector(); for (int i = 0; i < 7; i++) cats.addElement(new Cat(i)); cats.addElement(new Dog(7)); for (int i = 0; i < cats.size(); i++) ((Cat) cats.elementAt(i)).print(); } } |
//示例程式2 import java.util.*;
public class Stacks { static String[] months = { "1", "2", "3", "4" };
public static void main(String[] args) { Stack stk = new Stack(); for (int i = 0; i < months.length; i++) stk.push(months[i]); System.out.println(stk); System.out.println("element 2=" + stk.elementAt(2)); while (!stk.empty()) System.out.println(stk.pop()); } } |
//示例程式3 import java.util.*;
class Counter { int i = 1;
public String toString() { return Integer.toString(i); } }
public class Statistics { public static void main(String[] args) { Hashtable ht = new Hashtable(); for (int i = 0; i < 10000; i++) { Integer r = new Integer((int) (Math.random() * 20)); if (ht.containsKey(r)) ((Counter) ht.get(r)).i++; else ht.put(r, new Counter()); } System.out.println(ht); } } |
示例程式一:
1 import java.util.Vector; 2 3 class Cat { 4 private int catNumber; 5 6 Cat(int i) { 7 catNumber = i; 8 } 9 10 void print() { 11 System.out.println("Cat #" + catNumber); 12 } 13 } 14 15 class Dog { 16 private int dogNumber; 17 18 Dog(int i) { 19 dogNumber = i; 20 } 21 22 void print() { 23 System.out.println("Dog #" + dogNumber); 24 } 25 } 26 27 public class CatsAndDogs { 28 public static void main(String[] args) { 29 Vector cats = new Vector(); 30 for (int i = 0; i < 7; i++) 31 cats.addElement(new Cat(i)); 32 cats.addElement(new Dog(7)); 33 for (int i = 0; i < cats.size(); i++) 34 ((Cat) cats.elementAt(i)).print();//進行強制型別轉換 35 } 36 }
程式執行結果如下
出現這個是由於dog類無法強制型別轉換為cat類
修改之後的程式如下:
1 import java.util.Vector; 2 3 class Cat { 4 private int catNumber; 5 6 Cat(int i) { 7 catNumber = i; 8 } 9 10 void print() { 11 System.out.println("Cat #" + catNumber); 12 } 13 } 14 15 class Dog { 16 private int dogNumber; 17 18 Dog(int i) { 19 dogNumber = i; 20 } 21 22 void print() { 23 System.out.println("Dog #" + dogNumber); 24 } 25 } 26 27 public class CatsAndDogs { 28 public static void main(String[] args) { 29 Vector cats = new Vector(); 30 for (int i = 0; i < 7; i++) 31 cats.addElement(new Cat(i)); 32 cats.addElement(new Dog(7)); 33 for (int i = 0; i < cats.size(); i++) { 34 if(cats.elementAt(i)instanceof Cat)//instanceof指出物件是否是cat類 35 { 36 ((Cat) cats.elementAt(i)).print(); 37 } 38 else 39 ((Dog) cats.elementAt(i)).print(); 40 } 41 } 42 }
執行結果如下:
示例程式二:
1 import java.util.*; 2 3 public class Stacks { 4 static String[] months = { "1", "2", "3", "4" }; 5 6 public static void main(String[] args) { 7 Stack stk = new Stack(); 8 for (int i = 0; i < months.length; i++) 9 stk.push(months[i]);//進棧 10 System.out.println(stk); 11 System.out.println("element 2=" + stk.elementAt(2)); 12 while (!stk.empty()) 13 System.out.println(stk.pop());//出棧 14 } 15 }
程式執行結果如下:
示例程式三:
1 import java.util.*; 2 3 class Counter { 4 5 int i = 1; 6 7 public String toString()//把其他型別的資料轉化為字串型別的 8 9 { 10 11 return Integer.toString(i); 12 13 } 14 15 } 16 17 public class Statistics { 18 19 public static void main(String[] args) { 20 21 Hashtable ht = new Hashtable(); 22 23 for (int i = 0; i < 10000; i++) { 24 25 Integer r = new Integer((int) (Math.random() * 20));//生成0~1之間的隨機數 26 27 if (ht.containsKey(r)) 28 29 ((Counter) ht.get(r)).i++; 30 31 else 32 33 ht.put(r, new Counter()); 34 35 } 36 37 System.out.println(ht); 38 39 } 40 41 }
執行結果如下:
測試程式2:
l 使用JDK命令編輯執行ArrayListDemo和LinkedListDemo兩個程式,結合程式執行結果理解程式;
import java.util.*;
public class ArrayListDemo { public static void main(String[] argv) { ArrayList al = new ArrayList(); // Add lots of elements to the ArrayList... al.add(new Integer(11)); al.add(new Integer(12)); al.add(new Integer(13)); al.add(new String("hello")); // First print them out using a for loop. System.out.println("Retrieving by index:"); for (int i = 0; i < al.size(); i++) { System.out.println("Element " + i + " = " + al.get(i)); } } } |
import java.util.*; public class LinkedListDemo { public static void main(String[] argv) { LinkedList l = new LinkedList(); l.add(new Object()); l.add("Hello"); l.add("zhangsan"); ListIterator li = l.listIterator(0); while (li.hasNext()) System.out.println(li.next()); if (l.indexOf("Hello") < 0) System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } } |
l 在Elipse環境下編輯執行除錯教材360頁程式9-1,結合程式執行結果理解程式;
l 掌握ArrayList、LinkList兩個類的用途及常用API。
1.執行ArrayListDemo:
1 import java.util.*; 2 3 public class ArrayListDemo { 4 public static void main(String[] argv) { 5 ArrayList al = new ArrayList();//a1呼叫ArrayList類陣列 6 7 8 //向ArrayList中新增大量元素 9 al.add(new Integer(11)); 10 al.add(new Integer(12)); 11 al.add(new Integer(13)); 12 al.add(new String("hello")); 13 // 首先用一個for迴圈打印出來。 14 System.out.println("Retrieving by index:"); 15 for (int i = 0; i < al.size(); i++) { 16 System.out.println("Element " + i + " = " + al.get(i)); 17 } 18 } 19 }
執行結果如下:
2.執行LinkedListDemo
1 import java.util.*; 2 public class LinkedListDemo { 3 public static void main(String[] argv) { 4 LinkedList l = new LinkedList(); 5 l.add(new Object()); 6 l.add("Hello"); 7 l.add("zhangsan"); 8 ListIterator li = l.listIterator(0); 9 while (li.hasNext()) 10 System.out.println(li.next()); 11 if (l.indexOf("Hello") < 0) 12 System.err.println("Lookup does not work"); 13 else 14 System.err.println("Lookup works"); 15 } 16 }
執行結果如下:
3.執行除錯教材360頁程式9-1
1 package linkedList; 2 3 import java.util.*; 4 5 /** 6 * This program demonstrates operations on linked lists. 7 * @version 1.11 2012-01-26 8 * @author Cay Horstmann 9 */ 10 public class LinkedListTest 11 { 12 public static void main(String[] args) 13 { 14 List<String> a = new LinkedList<>();//建立一個泛型類,用a引用它 15 a.add("Amy"); 16 a.add("Carl"); 17 a.add("Erica"); 18 19 List<String> b = new LinkedList<>(); 20 b.add("Bob"); 21 b.add("Doug"); 22 b.add("Frances"); 23 b.add("Gloria"); 24 25 // 將a和b合併起來 26 27 ListIterator<String> aIter = a.listIterator();//遍歷a中的所有元素,且a中元素為string類 28 Iterator<String> bIter = b.iterator(); 29 30 while (bIter.hasNext()) 31 { 32 if (aIter.hasNext()) aIter.next(); 33 aIter.add(bIter.next()); 34 } 35 36 System.out.println(a); 37 38 // remove every second word from b 39 40 bIter = b.iterator(); 41 while (bIter.hasNext()) 42 { 43 bIter.next(); // skip one element 44 if (bIter.hasNext()) 45 { 46 bIter.next(); // skip next element 47 bIter.remove(); // remove that element 48 } 49 } 50 51 System.out.println(b); 52 53 // bulk operation: remove all words in b from a 54 55 a.removeAll(b); 56 57 System.out.println(a); 58 } 59 }
執行結果如下;
總結:
1.LinkedList類實現了List介面,允許null元素。此外LinkedList提供額外的get,remove,insert方法在 LinkedList的首部或尾部。
2.ArrayList實現了可變大小的陣列。
3.ArrayList方便查詢,佔用空間小。LinkedList方便新增刪除等修改操作,佔用空間大。
測試程式3:
l 執行SetDemo程式,結合執行結果理解程式;
import java.util.*; public class SetDemo { public static void main(String[] argv) { HashSet h = new HashSet(); //也可以 Set h=new HashSet() h.add("One"); h.add("Two"); h.add("One"); // DUPLICATE h.add("Three"); Iterator it = h.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } |
l 在Elipse環境下除錯教材365頁程式9-2,結合執行結果理解程式;瞭解HashSet類的用途及常用API。
l 在Elipse環境下除錯教材367頁-368程式9-3、9-4,結合程式執行結果理解程式;瞭解TreeSet類的用途及常用API。
1 import java.util.*; 2 public class SetDemo { 3 public static void main(String[] argv) { 4 HashSet h = new HashSet(); //也可以 Set h=new HashSet() 5 h.add("One"); 6 h.add("Two"); 7 h.add("One"); // DUPLICATE 8 h.add("Three"); 9 Iterator it = h.iterator(); 10 while (it.hasNext()) { 11 System.out.println(it.next()); 12 } 13 } 14 }
執行結果如下:
在Elipse環境下除錯教材365頁程式9-2,結合執行結果理解程式;瞭解HashSet類的用途及常用API。
1 package set; 2 3 import java.util.*; 4 5 /** 6 * This program uses a set to print all unique words in System.in. 7 * @version 1.12 2015-06-21 8 * @author Cay Horstmann 9 */ 10 public class SetTest 11 { 12 public static void main(String[] args) 13 { 14 Set<String> words = new HashSet<>(); // HashSet implements Set 15 long totalTime = 0; 16 17 try (Scanner in = new Scanner(System.in)) 18 { 19 while (in.hasNext()) 20 { 21 String word = in.next(); 22 long callTime = System.currentTimeMillis(); 23 words.add(word); 24 callTime = System.currentTimeMillis() - callTime; 25 totalTime += callTime; 26 } 27 } 28 29 Iterator<String> iter = words.iterator(); 30 for (int i = 1; i <= 20 && iter.hasNext(); i++) 31 System.out.println(iter.next()); 32 System.out.println(". . ."); 33 System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds."); 34 } 35 }
在Elipse環境下除錯教材367頁-368程式9-3、9-4,結合程式執行結果理解程式;瞭解TreeSet類的用途及常用API。
package treeSet; import java.util.*; /** * An item with a description and a part number. */ public class Item implements Comparable<Item> { private String description; private int partNumber; /** * Constructs an item. * * @param aDescription * the item's description * @param aPartNumber * the item's part number */ public Item(String aDescription, int aPartNumber) { description = aDescription; partNumber = aPartNumber; } /** * Gets the description of this item. * * @return the description */ public String getDescription() { return description; } public String toString() { return "[description=" + description + ", partNumber=" + partNumber + "]"; } public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Item other = (Item) otherObject; return Objects.equals(description, other.description) && partNumber == other.partNumber; } public int hashCode() { return Objects.hash(description, partNumber); } public int compareTo(Item other) { int diff = Integer.compare(partNumber, other.partNumber); return diff != 0 ? diff : description.compareTo(other.description); } }
執行結果如下:
測試程式4:
l 使用JDK命令執行HashMapDemo程式,結合程式執行結果理解程式;
import java.util.*; public class HashMapDemo { public static void main(String[] argv) { HashMap h = new HashMap(); // The hash maps from company name to address. h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Sun", "Mountain View, CA"); String queryString = "Adobe"; String resultString = (String)h.get(queryString); System.out.println("They are located in: " + resultString); } } |
l 在Elipse環境下除錯教材373頁程式9-6,結合程式執行結果理解程式;
l 瞭解HashMap、TreeMap兩個類的用途及常用API。
1.執行HashMapDemo程式,結合程式執行結果理解程式;
package treeSet; import java.util.*; public class HashMapDemo { public static void main(String[] argv) { HashMap h = new HashMap(); // The hash maps from company name to address. h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Sun", "Mountain View, CA"); String queryString = "Adobe";//訪問指定的關鍵字Adobe String resultString = (String)h.get(queryString); System.out.println("They are located in: " + resultString); } }
執行結果如下:
在Elipse環境下除錯教材373頁程式9-6,結合程式執行結果理解程式;
package map; import java.util.*; /** * This program demonstrates the use of a map with key type String and value type Employee. * @version 1.12 2015-06-21 * @author Cay Horstmann */ public class MapTest { public static void main(String[] args) { Map<String, Employee> staff = new HashMap<>(); staff.put("144-25-5464", new Employee("Amy Lee")); staff.put("567-24-2546", new Employee("Harry Hacker")); staff.put("157-62-7935", new Employee("Gary Cooper")); staff.put("456-62-5527", new Employee("Francesca Cruz")); // print all entries System.out.println(staff); // remove an entry staff.remove("567-24-2546"); // replace an entry staff.put("456-62-5527", new Employee("Francesca Miller")); // look up a value System.out.println(staff.get("157-62-7935")); // iterate through all entries staff.forEach((k, v) -> System.out.println("key=" + k + ", value=" + v)); } }
執行結果如下:
實驗2:結對程式設計練習:
l 關於結對程式設計:以下圖片是一個結對程式設計場景:兩位學習夥伴坐在一起,面對著同一臺顯示器,使用著同一鍵盤,同一個滑鼠,他們一起思考問題,一起分析問題,一起編寫程式。
l 關於結對程式設計的闡述可參見以下連結:
http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html
http://en.wikipedia.org/wiki/Pair_programming
l 對於結對程式設計中程式碼設計規範的要求參考:
http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html
以下實驗,就讓我們來體驗一下結對程式設計的魅力。
l 確定本次實驗結對程式設計合作伙伴;韓臘梅
l 各自執行合作伙伴實驗九程式設計練習1,結合使用體驗對所執行程式提出完善建議;
package gbfdb; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class A{ private static ArrayList<Test> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("D:\\身份證號.txt"); try { FileInputStream fis = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" "); String name = linescanner.next(); String number = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String province =linescanner.nextLine(); Test student = new Test(); student.setName(name); student.setnumber(number); student.setsex(sex); int a = Integer.parseInt(age); student.setage(a); student.setprovince(province); studentlist.add(student); } } catch (FileNotFoundException e) { System.out.println("學生資訊檔案找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("學生資訊檔案讀取錯誤"); e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("1:字典排序"); System.out.println("2:輸出年齡最大和年齡最小的人"); System.out.println("3:尋找老鄉"); System.out.println("4:尋找年齡相近的人"); System.out.println("5:退出"); String m = scanner.next(); switch (m) { case "1": Collections.sort(studentlist); System.out.println(studentlist.toString()); break; case "2": int max=0,min=100; int j,k1 = 0,k2=0; for(int i=1;i<studentlist.size();i++) { j=studentlist.get(i).getage(); if(j>max) { max=j; k1=i; } if(j<min) { min=j; k2=i; } } System.out.println("年齡最大:"+studentlist.get(k1)); System.out.println("年齡最小:"+studentlist.get(k2)); break; case "3": System.out.println("province?"); String find = scanner.next(); String place=find.substring(0,3); for (int i = 0; i <studentlist.size(); i++) { if(studentlist.get(i).getprovince().substring(1,4).equals(place)) System.out.println("province"+studentlist.get(i)); } break; case "4": System.out.println("年齡:"); int yourage = scanner.nextInt(); int near=agematched(yourage); int value=yourage-studentlist.get(near).getage(); System.out.println(""+studentlist.get(near)); break; case "5": isTrue = false; System.out.println("退出程式!"); break; default: System.out.println("輸入有誤"); } } } public static int agematched(int age) { int j=0,min=53,value=0,k=0; for (int i = 0; i < studentlist.size(); i++) { value=studentlist.get(i).getage()-age; if(value<0) value=-value; if (value<min) { min=value; k=i; } } return k; } }
package gbfdb; public class Test implements Comparable<Test> { private String name; private String number ; private String sex ; private int age; private String province; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getnumber() { return number; } public void setnumber(String number) { this.number = number; } public String getsex() { return sex ; } public void setsex(String sex ) { this.sex =sex ; } public int getage() { return age; } public void setage(int age) { this.age= age; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } public int compareTo(Test o) { return this.name.compareTo(o.getName()); } public String toString() { return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; } }
執行結果如下:
l 各自執行合作伙伴實驗十程式設計練習2,結合使用體驗對所執行程式提出完善建議;
package gbfdb; import java.util.Random; import java.util.Scanner; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Main{ public static void main(String[] args) { yunsuan counter=new yunsuan();//與其它類建立聯絡 PrintWriter out=null; try { out=new PrintWriter("D:/text.txt");//將檔案裡的內容讀入到D盤名叫text的檔案中 }catch(FileNotFoundException e) { System.out.println("檔案找不到"); e.printStackTrace(); } int sum=0; for(int i=0;i<10;i++) { int a=new Random().nextInt(100); int b=new Random().nextInt(100); Scanner in=new Scanner(System.in); //in.close(); switch((int)(Math.random()*4)) { case 0: System.out.println( ""+a+"+"+b+"="); int c1 = in.nextInt(); out.println(a+"+"+b+"="+c1); if (c1 == counter.plus(a, b)) { sum += 10; System.out.println("答案正確"); } else { System.out.println("答案錯誤"); } break ; case 1: if(a<b) { int temp=a; a=b; b=temp; }//為避免減數比被減數大的情況 System.out.println(""+a+"-"+b+"="); /*while((a-b)<0) { b = (int) Math.round(Math.random() * 100); }*/ int c2 = in.nextInt(); out.println(a+"-"+b+"="+c2); if (c2 == counter.minus(a, b)) { sum += 10; System.out.println("答案正確"); } else { System.out.println("答案錯誤"); } break ; case 2: System.out.println(""+a+"*"+b+"="); int c = in.nextInt(); out.println(a+"*"+b+"="+c); if (c == counter.multiply(a, b)) { sum += 10; System.out.println("答案正確"); } else { System.out.println("答案錯誤"); } break; case 3: while(b==0) { b = (int) Math.round(Math.random() * 100);//滿足分母不為0 } while(a%b!=0) { a = (int) Math.round(Math.random() * 100); b = (int) Math.round(Math.random() * 100); } System.out.println(""+a+"/"+b+"="); int c0= in.nextInt(); out.println(a+"/"+b+"="+c0); if (c0 == counter.divide(a, b)) { sum += 10; System.out.println("答案正確"); } else { System.out.println("答案錯誤"); } break; } } System.out.println("totlescore:"+sum); out.println(sum); out.close(); } }
package gbfdb; public class yunsuan <T>{ private T a; private T b; public void yunsaun() { a=null; b=null; } public void yunsuan(T a,T b) { this.a=a; this.b=b; } public int plus(int a,int b) { return a+b; } public int minus(int a,int b) { return a-b; } public int multiply(int a,int b) { return a*b; } public int divide(int a,int b) { if(b!=0 && a%b==0) return a/b; else return 0; } }
執行結果如下:
l 採用結對程式設計方式,與學習夥伴合作完成實驗九程式設計練習1;
package gbfdb; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Moom{ private static ArrayList<Mest> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("D:\\身份證號.txt"); try { FileInputStream fis = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" "); String name = linescanner.next(); String number = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String province =linescanner.nextLine(); Mest student = new Mest(); student.setName(name); student.setnumber(number); student.setsex(sex); int a = Integer.parseInt(age); student.setage(a); student.setprovince(province); studentlist.add(student); } } catch (FileNotFoundException e) { System.out.println("學生資訊檔案找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("學生資訊檔案讀取錯誤"); e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("1:字典排序"); System.out.println("2:輸出年齡最大和年齡最小的人"); System.out.println("3:尋找老鄉"); System.out.println("4:尋找年齡相近的人"); System.out.println("5:退出"); String m = scanner.next(); switch (m) { case "1": Collections.sort(studentlist); System.out.println(studentlist.toString()); break; case "2": int max=0,min=100; int j,k1 = 0,k2=0; for(int i=1;i<studentlist.size();i++) { j=studentlist.get(i).getage(); if(j>max) { max=j; k1=i; } if(j<min) { min=j; k2=i; } } System.out.println("年齡最大:"+studentlist.get(k1)); System.out.println("年齡最小:"+studentlist.get(k2)); break; case "3": System.out.println("家庭住址:"); String find = scanner.next(); String place=find.substring(0,3); for (int i = 0; i <studentlist.size(); i++) { if(studentlist.get(i).getprovince().substring(1,4).equals(place)) System.out.println("province"+studentlist.get(i)); } break; case "4": System.out.println("年齡:"); int yourage = scanner.nextInt(); int near=agematched(yourage); int value=yourage-studentlist.get(near).getage(); System.out.println(""+studentlist.get(near)); break; case "5": isTrue = false; System.out.println("退出程式!"); break; default: System.out.println("輸入錯誤"); } } } public static int agematched(int age) { int j=0,min=53,value=0,k=0; for (int i = 0; i < studentlist.size(); i++) { value=studentlist.get(i).getage()-age; if(value<0) value=-value; if (value<min) { min=value; k=i; } } return k; } }
package gbfdb; public class Mest implements Comparable<Mest> { private String name; private String number ; private String sex ; private int age; private String province; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getnumber() { return number; } public void setnumber(String number) { this.number = number; } public String getsex() { return sex ; } public void setsex(String sex ) { this.sex =sex ; } public int getage() { return age; } public void setage(int age) { this.age= age; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } public int compareTo(Mest o) { return this.name.compareTo(o.getName()); } public String toString() { return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; } }
執行結果如下: