王玉蘭201771010128《面向物件與程式設計(Java)》第十一週學習總結
一:理論知識部分:
(1)集合:集合(Collection或稱為容器)是一種包含多個元素並提供對所包含元素操作方法的類,其包含的元素可以由同一型別的物件組成,也可以由不同型別的物件組成。
A:集合類的作用:
– Java的集合類提供了一些基本資料結構的支援。
– 例如Vector、Hashtable、Stack等。
. 集合類的使用:
– Java的集合類包含在java.util包中。
– import java.util.*;
B:集合類的特點:1 只容納物件(陣列可以容納基本資料型別資料和物件。)
2集合類容納的物件都是Object類的例項,一旦把一個物件置入集合類中,它的類資訊將丟失,這樣設計的目的是為了集合類的通用性。
– 因為Object類是所有類的祖先,所以可以在這些集合中存放任何類的物件而不受限制,但切記在使用集合成員之前必須對它重新造型。
(2)vector類
Vector類類似長度可變的陣列。
Vector中只能存放物件。
Vector的元素通過下標進行訪問。
Vector類關鍵屬性:
– capacity表示集合最多能容納的元素個數。
– capacityIncrement表示每次增加多少容量。
– size表示集合當前元素個數。
(3)Stack類
Stack類是Vector的子類。
Stack類描述堆疊資料結構,即LIFO。
(4)Hashtable類。
Hashtable通過鍵來查詢元素。
Hashtable用雜湊碼(hashcode)來確定鍵。所
有物件都有一個雜湊碼,可以通過Object類的
hashCode()方法獲得。.
(5).集合框架中的基本介面:
A:Collection:集合層次中的根介面,JDK未提供這個介面的直接實現類。
B:Set:不能包含重複的元素。物件可能不是按存放的次序存放,也就是說不能像陣列一樣按索引的方式進行訪問,SortedSet是一個按照升序排列元素的Set。
C:List:是一個有序的集合,可以包含重複的元素。提供了按索引訪問的方式。
D:Map:包含了key-value對。Map不能包含重複的key。
E:SortedMap是一個按照升序排列key的Map。
(6)ArrayList
ArrayList:可以將其看作是能夠自動增長容量的陣列。
. 利用ArrayList的toArray()返回一個數組。
. Arrays.asList()返回一個列表。
. LinkedList是採用雙向迴圈連結串列實現的。
. 利用LinkedList實現棧(stack)、佇列(queue)、雙向佇列(double-ended queue )。
. ArrayList底層採用陣列完成,而LinkedList則是以一般的雙向連結串列(double-linked list)完成,其內每個物件除了資料本身外,還有兩個引用,分別指向前一個元素和後一個元素。
. 如果經常在List 中進行插入和刪除操作, 應該使用LinkedList,否則,使用ArrayList將更加快速。
(7)set
Set中的元素必須唯一。
. 新增到Set中的物件元素必須定義equals方法,以提供演算法來判斷欲新增進來的物件是否與已經存在的某物件相等,從而建立物件的唯一性。
. 實現Set 介面的類有HashSet,TreeSet。
(8)Map介面的方法
boolean containsKey(Object k) 檢查呼叫對映中是否包含關鍵字K
. boolean containsValue(Object v) 檢查呼叫對映中是否包含值V
. Object get(Object k) 返回與關鍵字k相關聯的值
. boolean isEmpty( ) 如果呼叫對映是空的,則返回true;否則返回false
. Object put(Object k, Object v)將一個鍵值對加入呼叫對映
. Object remove(Object k) 刪除關鍵字等於k的鍵值對
. int size( ) 返回對映中關鍵字/值對的個數
. Set entrySet( ) 返回包含了對映中的項的集合(Set)。該集合包含了型別Map.Entry的物件。這個方法為呼叫對映提供了一個集合“檢視”
. Set keySet( ) 返回一個包含呼叫對映中關鍵字的集合(Set)。這個方法為呼叫對映的關鍵字提供了一個集合“檢視”
. Collection values( )返回一個包含了對映中的值的類集。這個方法為對映中的值提供了一個類集“檢視”
(9)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); } } |
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();//建立了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++) //instanceof用來判斷記憶體中實際物件 if (cats.elementAt(i) instanceof Cat) { ((Cat) cats.elementAt(i)).print(); } else { ((Dog) cats.elementAt(i)).print(); } } }
執行結果:
修改後:
import java.util.*; public class Stacks { static String[] months = { "1", "2", "3", "4" }; public static void main(String[] args) { Stack stk = new Stack();//建立了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()); } }
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();//建立了Hashtable類 for (int i = 0; i < 10000; i++) { //用整形包裝器生成了20個隨機數 Integer r = new Integer((int) (Math.random() * 20)); //通過物件呼叫containskey方法 if (ht.containsKey(r)) //判斷r值是不是ht裡的健值,如果是返回ture,不是返回Flash ((Counter) ht.get(r)).i++; else //通過Counter類物件引用類內部的屬性 ht.put(r, new Counter()); //呼叫put方法向hash表中新增資訊(預設的構造器,其屬性值是初始值1 } System.out.println(ht); } }
測試程式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"); } } |
import java.util.*; public class ArrayListDemo { public static void main(String[] argv) { ArrayList al = new ArrayList();//建立了Arraylist陣列 // Add lots of elements to the ArrayList... //用Add來新增物件且可以過載 al.add(new Integer(11));//在當前位置新增一個元素11 al.add(new Integer(12)); al.add(new Integer(13)); al.add(new String("hello")); System.out.println(al.size()); //首先用一個For迴圈打印出來 // 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();//構建LinkedList連結串列類 l.add(new Object());//在當前位置新增一個物件 l.add("Hello"); l.add("zhangsan"); System.out.println(l.size());//輸出l的長度 ListIterator li = l.listIterator(0);//用迭代器生成物件 while (li.hasNext())//如果存在可訪問的元素可以返回ture 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。
package linkedList; import java.util.*; /** * This program demonstrates operations on linked lists. * @version 1.12 2018-04-10 * @author Cay Horstmann */ public class LinkedListTest { public static void main(String[] args) { var a = new LinkedList<String>();// a.add("Amy"); a.add("Carl"); a.add("Erica"); var b = new LinkedList<String>(); b.add("Bob"); b.add("Doug"); b.add("Frances"); b.add("Gloria"); // 將單詞從b合併為a ListIterator<String> aIter = a.listIterator(); Iterator<String> bIter = b.iterator(); while (bIter.hasNext()) { if (aIter.hasNext()) aIter.next(); aIter.add(bIter.next()); } System.out.println(a); //從b中刪除每個第二個單詞 bIter = b.iterator(); while (bIter.hasNext()) { bIter.next(); // skip one element if (bIter.hasNext()) { bIter.next(); // skip next element bIter.remove(); // remove that element //刪除該元素 } } System.out.println(b); // bulk operation: remove all words in b from a a.removeAll(b); System.out.println(a); } }
執行結果:
測試程式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()); } } } |
package linkedList; 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。
package set; import java.util.*; /** * This program uses a set to print all unique words in System.in. * @version 1.12 2015-06-21 * @author Cay Horstmann */ public class SetTest { public static void main(String[] args) { var words = new HashSet<String>(); long totalTime = 0; try (var in = new Scanner(System.in)) { while (in.hasNext()) { String word = in.next(); long callTime = System.currentTimeMillis(); words.add(word); callTime = System.currentTimeMillis() - callTime; totalTime += callTime; } } Iterator<String> iter = words.iterator(); for (int i = 1; i <= 20 && iter.hasNext(); i++) System.out.println(iter.next()); System.out.println(". . ."); System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds."); } }
l 在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; var 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); } }
package treeSet; import java.util.*; /** * This program sorts a set of Item objects by comparing their descriptions. * @version 1.13 2018-04-10 * @author Cay Horstmann */ public class TreeSetTest { public static void main(String[] args) { var parts = new TreeSet<Item>(); parts.add(new Item("Toaster", 1234)); parts.add(new Item("Widget", 4562)); parts.add(new Item("Modem", 9912)); System.out.println(parts); var sortByDescription = new TreeSet<Item>( Comparator.comparing(Item::getDescription)); sortByDescription.addAll(parts); System.out.println(sortByDescription); } }
測試程式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); } } |
import java.util.*; public class HashMapDemo { public static void main(String[] argv) { HashMap h = new HashMap(); // 從公司名稱到地址的雜湊對映 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。
package map; /** * A minimalist employee class for testing purposes. */ public class Employee { private String name; private double salary; /** * Constructs an employee with $0 salary. * @param n the employee name */ public Employee(String name) { this.name = name; salary = 0; } public String toString() { return "[name=" + name + ", salary=" + salary + "]"; } }
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) { var staff = new HashMap<String, Employee>(); 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")); // 列印所有的病例 System.out.println(staff); // 刪除條目 staff.remove("567-24-2546");
//替換條目 staff.put("456-62-5527", new Employee("Francesca Miller")); // 查詢值 System.out.println(staff.get("157-62-7935")); // 遍歷所有的腸道 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,結合使用體驗對所執行程式提出完善建議;
l 採用結對程式設計方式,與學習夥伴合作完成實驗九程式設計練習1;
夥伴的程式碼:
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 M{ 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; } }
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 練習2; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class Suanshu1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); Suanshu Suanshu=new Suanshu(); PrintWriter output = null; try { output = new PrintWriter("ss.txt"); } catch (Exception e) { //e.printStackTrace(); } int sum = 0; for (int i = 1; i < 11; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int s = (int) Math.round(Math.random() * 3); switch(s) { case 1: System.out.println(i+": "+a+"/"+b+"="); while(b==0){ b = (int) Math.round(Math.random() * 100); } double c = in.nextDouble(); output.println(a+"/"+b+"="+c); if (c == Suanshu.chu_fa(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; case 2: System.out.println(i+": "+a+"*"+b+"="); int c1 = in.nextInt(); output.println(a+"*"+b+"="+c1); if (c1 == Suanshu.chen_fa(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break; case 3: System.out.println(i+": "+a+"+"+b+"="); int c2 = in.nextInt(); output.println(a+"+"+b+"="+c2); if (c2 == Suanshu.jia_fa(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break ; case 4: System.out.println(i+": "+a+"-"+b+"="); int c3 = in.nextInt(); output.println(a+"-"+b+"="+c3); if (c3 == Suanshu.jian_fa(a, b)) { sum += 10; System.out.println("恭喜答案正確"); } else { System.out.println("抱歉,答案錯誤"); } break ; } } System.out.println("成績"+sum); output.println("成績:"+sum); output.close(); } }
package 練習2; public class Suanshu { private int a; private int b; public int jia_fa(int a,int b) { return a+b; } public int jian_fa(int a,int b) { if((a-b)<0) return 0; else return a-b; } public int chen_fa(int a,int b) { return a*b; } public int chu_fa(int a,int b) { if(b!=0) return a/b; else return 0; } }
l 採用結對程式設計方式,與學習夥伴合作完成實驗九程式設計練習1;
package ID; 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 Main{ private static ArrayList<People> Peoplelist; public static void main(String[] args) { Peoplelist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("D:\\java\\1\\身份證號.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 ID = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String place =linescanner.nextLine(); People People = new people(); People.setname(name); People.setID(ID); People.setsex(sex); int a = Integer.parseInt(age); People.setage(a); People.setbirthplace(place); Peoplelist.add(People); } } catch (FileNotFoundException e) { System.out.println("查詢不到資訊"); e.printStackTrace(); } catch (IOException e) { System.out.println("資訊讀取有誤"); e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("————————————————————————————————————————"); System.out.println("1:按姓名字典序輸出人員資訊"); System.out.println("2:查詢最大年齡人員資訊和最小年齡人員資訊"); System.out.println("3:輸入你的年齡,查詢年齡與你最近人的所有資訊"); System.out.println("4:查詢人員中是否有你的同鄉"); int nextInt = scanner.nextInt(); switch (nextInt) { case 1: Collections.sort( Peoplelist); System.out.println( Peoplelist.toString()); break; case 2: int max=0,min=100;int j,k1 = 0,k2=0; for(int i=1;i< Peoplelist.size();i++) { j= Peoplelist.get(i).getage(); if(j>max) { max=j; k1=i; } if(j<min) { min=j; k2=i; } } System.out.println("年齡最大:"+ Peoplelist.get(k1)); System.out.println("年齡最小:"+ Peoplelist.get(k2)); break; case 3: System.out.println("place?"); String find = scanner.next(); String place=find.substring(0,3); String place2=find.substring(0,3); for (int i = 0; i < Peoplelist.size(); i++) { if( Peoplelist.get(i).getbirthplace().substring(1,4).equals(place)) System.out.println(Peoplelist.get(i)); } break; case 4: System.out.println("年齡:"); int yourage = scanner.nextInt(); int near=agenear(yourage); int d_value=yourage-Peoplelist.get(near).getage(); System.out.println(""+Peoplelist.get(near)); /* for (int i = 0; i < Peoplelist.size(); i++) { int p=Personlist.get(i).getage()-yourage; if(p<0) p=-p; if(p==d_value) System.out.println(Peoplelist.get(i)); } */ break; case 5: isTrue = false; System.out.println("退出程式!"); break; default: System.out.println("輸入有誤"); } } } public static int agenear(int age) { int min=25,d_value=0,k=0; for (int i = 0; i < Peoplelist.size(); i++) { d_value= Peoplelist.get(i).getage()-age; if(d_value<0) d_value=-d_value; if (d_value<min) { min=d_value; k=i; } } return k; } }
package ID; public abstract class People implements Comparable<People> { private String name; private String ID; private int age; private String sex; private String birthplace; public String getname() { return name; } public void setname(String name) { this.name = name; } public String getID() { return ID; } public void setID(String ID) { this.ID= ID; } public int getage() { return age; } public void setage(int age) { // int a = Integer.parseInt(age); this.age= age; } public String getsex() { return sex; } public void setsex(String sex) { this.sex= sex; } public String getbirthplace() { return birthplace; } public void setbirthplace(String birthplace) { this.birthplace= birthplace; } public int compareTo(People o) { return this.name.compareTo(o.getname()); } public String toString() { return name+"\t"+sex+"\t"+age+"\t"+ID+"\t"+birthplace+"\n"; } }
|
l 採用結對程式設計方式,與學習夥伴合作完成實驗九程式設計練習2;
import java.io .FileNotFoundException; import java.io .PrintWriter; import java.util.Scanner; public class jisuan{ public static void main(String[] args) { Scanner in = new Scanner(System.in ); Caculator1 computing=new Caculator1(); PrintWriter output = null; try { output = new PrintWriter("Caculator.txt"); } catch (Exception e) { } int sum = 0; for (int i = 1; i < 11; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int s = (int) Math.round(Math.random() * 3); switch(s) { case 1: System.out.println(i+": "+a+"/"+b+"="); while(b==0){ b = (int) Math.round(Math.random() * 100); } double c = in.nextDouble(); output.println(a+"/"+b+"="+c); if (c == (double)computing.division(a, b)) { sum += 10; System.out.println("正確"); } else { System.out.println("錯誤"); } break; case 2: System.out.println(i+": "+a+"*"+b+"="); int c1 = in.nextInt(); output.println(a+"*"+b+"="+c1); if (c1 == computing.multiplication(a, b)) { sum += 10; System.out.println("正確"); } else { System.out.println("錯誤"); } break; case 3: System.out.println(i+": "+a+"+"+b+"="); int c2 = in.nextInt(); output.println(a+"+"+b+"="+c2); if (c2 == computing.addition(a, b)) { sum += 10; System.out.println("正確"); } else { System.out.println("錯誤"); } break ; case 4: System.out.println(i+": "+a+"-"+b+"="); int c3 = in.nextInt(); output.println(a+"-"+b+"="+c3); if (c3 == computing.subtraction(a, b)) { sum += 10; System.out.println("正確"); } else { System.out.println("錯誤"); } break ; } } System.out.println("scores:"+sum); output.println("scores:"+sum); output.close(); } }
實驗總結:本章先回顧了資料結構中的相關知識,然後介紹集合類的特點及作用,通過實驗驗證了vector類,stack類,hashtable等的用法,在週四的實驗課上,在學長的示範下,初次知道了instanceof的用法,換言之瞭解API是根本,在不會相關的知識時及時查詢,接下來就要好好複習資料結構的內容了,因為掌握的不好。