201771010112罗松《面向对象程序设计(java)》第十一周学习总结
?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命令運行編輯、運行以下三個示例程序,結合運行結果理解程序;
掌握Vetor、Stack、Hashtable三個類的用途及常用API。
import java.util.Vector;//示例程序1class 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++)if(cats.elementAt(i)instanceof Cat)// instanceof運算符是用來指出對象是否是特定類的一個實例 { ((Cat) cats.elementAt(i)).print();}else {((Dog) 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]);//放入一個i值System.out.println(stk);System.out.println("element 2=" + stk.elementAt(2));//element表示一個節點while (!stk.empty())System.out.println(stk.pop());//出棧操作 } }Stacks結果:
示例三:
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();//生成集合類Hashtablefor (int i = 0; i < 10000; i++) //生成循環體 {Integer r = new Integer((int) (Math.random() * 20));//隨機生成實數定義為整型if (ht.containsKey(r))((Counter) ht.get(r)).i++;//用來判斷r是否為一個間值elseht.put(r, new Counter());//創建新的Counter對象 }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來添加對象且可以重載// 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"));System.out.println(al.size());//輸出al的長度// 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));}} }ArrayListDemo mport 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");//add方法可以重載 ListIterator li = l.listIterator(0);//迭代器生成li對象while (li.hasNext())//hasNext方法用來返回迭代器的對象System.out.println(li.next());if (l.indexOf("Hello") < 0) //生成循環語句判斷最后結果 System.err.println("Lookup does not work");elseSystem.err.println("Lookup works");} }LinkedListDemo測試程序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"); // DUPLICATEh.add("Three");Iterator it = h.iterator();while (it.hasNext()) //hasNext方法 {System.out.println(it.next());}} }SetDemo- ?在Elipse環境下調試教材365頁程序9-2,結合運行結果理解程序;了解HashSet類的用途及常用API。
小結:HashSet類中存放的對象不能重復,不能保證元素的排列順序,順序有可能發生變化。
在Elipse環境下調試教材367頁-368程序9-3、9-4,結合程序運行結果理解程序;了解TreeSet類的用途及常用API。
package treeSet;import java.util.*;/*** This program sorts a set of item by comparing their descriptions.* @version 1.12 2015-06-21* @author Cay Horstmann*/ public class TreeSetTest {public static void main(String[] args){SortedSet<Item> parts = new TreeSet<>();parts.add(new Item("Toaster", 1234));//add方法parts.add(new Item("Widget", 4562));parts.add(new Item("Modem", 9912));System.out.println(parts);NavigableSet<Item> sortByDescription = new TreeSet<>(Comparator.comparing(Item::getDescription));sortByDescription.addAll(parts);System.out.println(sortByDescription);} }TreeSetTest package treeSet;import java.util.*;/*** An item with a description and a part number.*/ public class Item implements Comparable<Item>//Item類實現Comparable接口 {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);} }Item小結:TreeSet是一種自帶排序的set,TreeSet可以確保集合元素處于排序狀態。TreeSet支持兩種排序方式,自然排序 和定制排序。
測試程序4:
使用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,結合程序運行結果理解程序;
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<>();//HashMap implements Mapstaff.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));} }l?實驗2:結對編程練習:
關于結對編程:以下圖片是一個結對編程場景:兩位學習伙伴坐在一起,面對著同一臺顯示器,使用著同一鍵盤,同一個鼠標,他們一起思考問題,一起分析問題,一起編寫程序。
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?各自運行合作伙伴實驗十編程練習2,結合使用體驗對所運行程序提出完善建議;
1、合作伙伴:張云飛
- 采用結對編程方式,與學習伙伴合作完成實驗九編程練習1;?
l?各自運行合作伙伴實驗十編程練習2,結合使用體驗對所運行程序提出完善建議;
import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner;public class calculator {public static void main(String[] args) {Scanner in = new Scanner(System.in);Count count=new Count();PrintWriter out = null;try {out = new PrintWriter("test.txt");int sum = 0;for (int i = 1; i <=10; i++) {int a = (int) Math.round(Math.random() * 100);int b = (int) Math.round(Math.random() * 100);int menu = (int) Math.round(Math.random() * 3);switch (menu) {case 0:System.out.println(i+":"+a + "+" + b + "=");int c1 = in.nextInt();out.println(a + "+" + b + "=" + c1);if (c1 == (a + b)) {sum += 10;System.out.println("恭喜答案正確");} else {System.out.println("抱歉,答案錯誤");}break;case 1:while (a < b) {b = (int) Math.round(Math.random() * 100);}System.out.println(i+":"+a + "-" + b + "=");int c2 = in.nextInt();out.println(a + "-" + b + "=" + c2);if (c2 == (a - b)) {sum += 10;System.out.println("恭喜答案正確");} else {System.out.println("抱歉,答案錯誤");}break;case 2:System.out.println(i+":"+a + "*" + b + "=");int c3 = in.nextInt();out.println(a + "*" + b + "=" + c3);if (c3 == a * b) {sum += 10;System.out.println("恭喜答案正確");} else {System.out.println("抱歉,答案錯誤");}break;case 3:while(b == 0){b = (int) Math.round(Math.random() * 100);}while(a % b != 0){a = (int) Math.round(Math.random() * 100);}System.out.println(i+":"+a + "/" + b + "=");int c4 = in.nextInt();if (c4 == a / b) {sum += 10;System.out.println("恭喜答案正確");} else {System.out.println("抱歉,答案錯誤");}break;}}System.out.println("你的得分為" + sum);out.println("你的得分為" + sum);out.close();} catch (FileNotFoundException e) {e.printStackTrace();}}}calculate public class Count<T> {private T a;private T b;public Count() {a=null;b=null;}public Count(T a,T b) {this.a=a;this.b=b;}public int count1(int a,int b) {return a+b;}public int count2(int a,int b) {return a-b;}public int count3(int a,int b) {return a*b;}public int count4(int a,int b) {return a/b;} }countl?采用結對編程方式,與學習伙伴合作完成實驗九編程練習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.List; import java.util.Scanner;public class Xinxi {private static ArrayList<Student> 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();Student student = new Student();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) {//添加的異常處理語句try{ }catch{ }語句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.尋找老鄉");System.out.println("5.退出");String n = scanner.next();switch (n) {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("同鄉" + studentlist.get(i));}break;case "4":System.out.println("年齡:");int yourage = scanner.nextInt();int near = agenear(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 agenear(int age) {int j = 0, min = 53, value = 0, flag = 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;flag = i;}}return flag;}}xinxixinxi public class Student implements Comparable<Student> {private String name;private String number;private String sex;private String province;private int age;public void setName(String name) {// TODO 自動生成的方法存根this.name = name;}public String getName() {// TODO 自動生成的方法存根return name;}public void setnumber(String number) {// TODO 自動生成的方法存根this.number = number;}public String getNumber() {// TODO 自動生成的方法存根return number;}public void setsex(String sex) {// TODO 自動生成的方法存根this.sex = sex;}public String getsex() {// TODO 自動生成的方法存根return sex;}public void setprovince(String province) {// TODO 自動生成的方法存根this.province = province;}public String getprovince() {// TODO 自動生成的方法存根return province;}public void setage(int a) {// TODO 自動生成的方法存根this.age = age;}public int getage() {// TODO 自動生成的方法存根return age;}public int compareTo(Student o) {return this.name.compareTo(o.getName());}public String toString() {return name + "\t" + sex + "\t" + age + "\t" + number + "\t" + province + "\n";} }student類studentl?采用結對編程方式,與學習伙伴合作完成實驗十編程練習2。
import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner;public class calculator {public static void main(String[] args) {Scanner in = new Scanner(System.in);Count count=new Count();PrintWriter out = null;try {out = new PrintWriter("test.txt");int sum = 0;for (int i = 1; i <=10; i++) {int a = (int) Math.round(Math.random() * 100);int b = (int) Math.round(Math.random() * 100);int menu = (int) Math.round(Math.random() * 3);switch (menu) {case 0:System.out.println(i+":"+a + "+" + b + "=");int c1 = in.nextInt();out.println(a + "+" + b + "=" + c1);if (c1 == (a + b)) {sum += 10;System.out.println("恭喜答案正確");} else {System.out.println("抱歉,答案錯誤");}break;case 1:while (a < b) {b = (int) Math.round(Math.random() * 100);}System.out.println(i+":"+a + "-" + b + "=");int c2 = in.nextInt();out.println(a + "-" + b + "=" + c2);if (c2 == (a - b)) {sum += 10;System.out.println("恭喜答案正確");} else {System.out.println("抱歉,答案錯誤");}break;case 2:System.out.println(i+":"+a + "*" + b + "=");int c3 = in.nextInt();out.println(a + "*" + b + "=" + c3);if (c3 == a * b) {sum += 10;System.out.println("恭喜答案正確");} else {System.out.println("抱歉,答案錯誤");}break;case 3:while(b == 0){b = (int) Math.round(Math.random() * 100);}while(a % b != 0){a = (int) Math.round(Math.random() * 100);}System.out.println(i+":"+a + "/" + b + "=");int c4 = in.nextInt();if (c4 == a / b) {sum += 10;System.out.println("恭喜答案正確");} else {System.out.println("抱歉,答案錯誤");}break;}}System.out.println("你的得分為" + sum);out.println("你的得分為" + sum);out.close();} catch (FileNotFoundException e) {e.printStackTrace();}}}calculate public class Count<T> {private T a;private T b;public Count() {a=null;b=null;}public Count(T a,T b) {this.a=a;this.b=b;}public int count1(int a,int b) {return a+b;}public int count2(int a,int b) {return a-b;}public int count3(int a,int b) {return a*b;}public int count4(int a,int b) {return a/b;} }count實驗總結:
?
?通過這周的學習,我對Vetor、Stack、Hashtable三個類的用途及常用API有了大致的了解,還大致了解了java集合框架體系組成;基本?掌握ArrayList、LinkList兩個類的用途及常用API。了解了HashSet類、TreeSet類的用途及常用API和HashMap、TreeMap兩個類的用途及常用API;
不過上述這些都只是有了一個初步的了解,要做到運用自如還要深入研究,苦下功夫。這周學習還有個最大的不同就是體驗了程序開發中兩人合作的感覺,從有意見不同到最后解決,那個過程很讓人享受,有種競爭感和成就感,總之這周收獲很大,今后的學習會更加努力!
?
轉載于:https://www.cnblogs.com/xuezhiqian/p/9941647.html
總結
以上是生活随笔為你收集整理的201771010112罗松《面向对象程序设计(java)》第十一周学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js字符转译
- 下一篇: 15、Spark_RDD算子——Aggr