201771010128王玉蘭《面向物件程式設計(Java)》第十週學習總結
第一部分:理論知識部分總結:
(1) 定義簡單泛型類:
A:泛型:也稱引數化型別(parameterizedtype),就是在定義類、介面和方法時,通過型別引數指 示將要處理的物件型別。
B:泛型程式設計(Genericprogramming):編寫 程式碼可以被很多不同型別的物件所重用。
C: 一個泛型類(genericclass)就是具有一個或多 個型別變數的類,即建立用型別作為引數的類。
(2)泛型方法(可以定義在普通類中,也可以定義在泛型類中)除了泛型類外,還可以只單獨定義一個方法作 為泛型方法,用於指定方法引數或者返回值為 泛型型別,留待方法呼叫時確定。
(3):泛型變數的限定:定義泛型變數的上界用extends,下界用super.
A:上下界的說明:a: extends關鍵字所宣告的上界既可以是一個類, 也可以是一個介面;b;一個型別變數或萬用字元可以有多個限定,限定類 型用“&”分割。
c: 通過使用super關鍵字可以固定泛型引數的型別為某種 型別或者其超類;
d: 當程式希望為一個方法的引數限定型別時,通常可以使 用下限萬用字元.
(4)萬用字元型別 :萬用字元 –“?”符號表明引數的型別可以是任何一種類 型,它和引數T的含義是有區別的。T表示一種 未知型別,而“?”表示任何一種型別。這種 萬用字元一般有以下三種用法:
–單獨的?,用於表示任何型別。
–? extends type,表示帶有上界。
–? super type,表示帶有下界。
第二部分:實驗
1、實驗目的與要求
(1) 理解泛型概念;
(2) 掌握泛型類的定義與使用;
(3) 掌握泛型方法的宣告與使用;
(4) 掌握泛型介面的定義與實現;
(5)瞭解泛型程式設計,理解其用途。
2、實驗內容和步驟
實驗1: 匯入第8章示例程式,測試程式並進行程式碼註釋。
測試程式1:
l 編輯、除錯、執行教材311、312頁 程式碼,結合程式執行結果理解程式;
l 在泛型類定義及使用程式碼處添加註釋;
l 掌握泛型類的定義及使用。
package pair1; /** * @version 1.00 2004-05-10 * @author Cay Horstmann */ public class Pair<T> //Pair類引入一個型別變數T { private T first;//類定義中的型別變數指定方法的返回型別以及域和區域性變數的型別 private T second; public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T getFirst() { return first; } public T getSecond() { return second; } public void setFirst(T newValue) { first = newValue; } public void setSecond(T newValue) { second = newValue; } }
package pair1; /** * @version 1.01 2012-01-26 * @author Cay Horstmann */ public class PairTest1 { public static void main(String[] args) { String[] words = { "Mary", "had", "a", "little", "lamb" };//初始化一個String物件陣列 Pair<String> mm = ArrayAlg.minmax(words);//通過類名ArrayAlg呼叫minmax方法 System.out.println("min = " + mm.getFirst()); System.out.println("max = " + mm.getSecond()); } } class ArrayAlg//泛型類 { /** * Gets the minimum and maximum of an array of strings. * @param a an array of strings * @return a pair with the min and max value, or null if a is null or empty */ public static Pair<String> minmax(String[] a)//例項化以後的pair類物件 { if (a == null || a.length == 0) return null; String min = a[0]; String max = a[0]; for (int i = 1; i < a.length; i++) { if (min.compareTo(a[i]) > 0) min = a[i]; if (max.compareTo(a[i]) < 0) max = a[i]; } return new Pair<>(min, max);//帶引數的構造器 } }
測試程式2:
l 編輯、除錯執行教材315頁 PairTest2,結合程式執行結果理解程式;
l 在泛型程式設計程式碼處新增相關注釋;
l 掌握泛型方法、泛型變數限定的定義及用途。
package pair2; import java.time.LocalDate; import pair1.Pair; /** * @version 1.02 2015-06-21 * @author Cay Horstmann */ public class PairTest2 { public static void main(String[] args) { LocalDate[] birthdays = { LocalDate.of(1906, 12, 9), // G. Hopper LocalDate.of(1815, 12, 10), // A. Lovelace LocalDate.of(1903, 12, 3), // J. von Neumann LocalDate.of(1910, 6, 22), // K. Zuse }; Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);//通過類名呼叫minmax 方法 System.out.println("min = " + mm.getFirst()); System.out.println("max = " + mm.getSecond()); } } class ArrayAlg { /** Gets the minimum and maximum of an array of objects of type T. @param a an array of objects of type T @return a pair with the min and max value, or null if a is null or empty */ public static <T extends Comparable> Pair<T> minmax(T[] a) //extends表示上界約束的泛型方法 { if (a == null || a.length == 0) return null;//a.length 是陣列的一個屬性 T min = a[0]; T max = a[0]; for (int i = 1; i < a.length; i++) { if (min.compareTo(a[i]) > 0) min = a[i]; if (max.compareTo(a[i]) < 0) max = a[i]; } return new Pair<>(min, max); } }
測試程式3:
l 用除錯執行教材335頁 PairTest3,結合程式執行結果理解程式;
l 瞭解萬用字元型別的定義及用途。
package pair3; import pair1.Pair; /** * @version 1.01 2012-01-26 * @author Cay Horstmann */ public class PairTest3 { public static void main(String[] args) { Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);//建立了Manager物件 Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15); Pair<Manager> buddies = new Pair<Manager>(ceo, cfo); //例項化pair物件 printBuddies(buddies); ceo.setBonus(1000000);//更改器 cfo.setBonus(500000); Manager[] managers = { ceo, cfo }; Pair<Employee> result = new Pair<Employee>();//尖括號裡既可以用Manager,也可以用Employee minmaxBonus(managers, result); System.out.println("first: " + result.getFirst().getName() + ", second: " + result.getSecond().getName()); maxminBonus(managers, result); System.out.println("first: " + result.getFirst().getName() + ", second: " + result.getSecond().getName()); } public static void printBuddies(Pair<? extends Employee> p)//?是萬用字元,extends表示帶有上界 { Employee first = p.getFirst();//訪問器方法 Employee second = p.getSecond(); System.out.println(first.getName() + " and " + second.getName() + " are buddies."); } public static void minmaxBonus(Manager[] a, Pair<? super Manager> result) { if (a.length == 0) return; Manager min = a[0]; Manager max = a[0]; for (int i = 1; i < a.length; i++) { if (min.getBonus() > a[i].getBonus()) min = a[i];//訪問器方法 if (max.getBonus() < a[i].getBonus()) max = a[i]; } result.setFirst(min); result.setSecond(max); } public static void maxminBonus(Manager[] a, Pair<? super Manager> result)//super表示帶有下界的泛型方法 { minmaxBonus(a, result); PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type } // Can't write public static <T super manager> . . . } class PairAlg//泛型類 { public static boolean hasNulls(Pair<?> p) { return p.getFirst() == null || p.getSecond() == null; } public static void swap(Pair<?> p) { swapHelper(p); }
public static <T> void swapHelper(Pair<T> p)
//限定泛型類Pair型別變數的下界為p;
{ T t = p.getFirst();
p.setFirst(p.getSecond());
p.setSecond(t); } }
實驗2:程式設計練習:
程式設計練習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.Scanner; import java.util.Collections;//對集合進行排序、查詢、修改等; public class Test { private static ArrayList<Citizen> citizenlist; public static void main(String[] args) { citizenlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("E:/java/身份證號.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 birthplace = linescanner.nextLine(); Citizen citizen = new Citizen(); citizen.setName(name); citizen.setId(id); citizen.setSex(sex); // 將字串轉換成10進位制數 int ag = Integer.parseInt(age); citizen.setage(ag); citizen.setBirthplace(birthplace); citizenlist.add(citizen); } } 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.退出"); int nextInt = scanner.nextInt(); switch (nextInt) { case 1: Collections.sort(citizenlist); System.out.println(citizenlist.toString()); break; case 2: int max = 0, min = 100; int m, k1 = 0, k2 = 0; for (int i = 1; i < citizenlist.size(); i++) { m = citizenlist.get(i).getage(); if (m > max) { max = m; k1 = i; } if (m < min) { min = m; k2 = i; } } System.out.println("年齡最大:" + citizenlist.get(k1)); System.out.println("年齡最小:" + citizenlist.get(k2)); break; case 3: System.out.println("出生地:"); String find = scanner.next(); String place = find.substring(0, 3); for (int i = 0; i < citizenlist.size(); i++) { if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place)) System.out.println("出生地" + citizenlist.get(i)); } break; case 4: System.out.println("年齡:"); int yourage = scanner.nextInt(); int near = peer(yourage); int j = yourage - citizenlist.get(near).getage(); System.out.println("" + citizenlist.get(near)); break; case 5: isTrue = false; System.out.println("程式已退出!"); break; default: System.out.println("輸入有誤"); } } } public static int peer(int age) { int flag = 0; int min = 53, j = 0; for (int i = 0; i < citizenlist.size(); i++) { j = citizenlist.get(i).getage() - age; if (j < 0) j = -j; if (j < min) { min = j; flag = i; } } return flag; } }
public class Student implements Comparable<Student> { 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) { // int a = Integer.parseInt(age); this.age= age; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } 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"; } }
程式總體說明:由主類Test和子類Student組成
模組說明:main方法的使用
A: 確定主函式,實現題目所要求的功能
B::將檔案資訊匯入進去,儲存到相應的包下
C:進行編輯,執行結果,完成程式
目前程式設計存在的困難與問題:
A:讀取檔案的位置,即路徑是否準確
B:實現的功能要求比較複雜,掌握的知識過少,解決程式碼錯誤時消耗時間過長,基礎知識不牢固
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(); } }
public class jiusuan_class { private int a; private int b; public int addition(int a,int b) { return a+b; } public int subtraction(int a,int b) { if((a-b)<0) return 0; else return a-b; } public int multiplication(int a,int b) { return a*b; } public int division(int a,int b) { if(b!=0) return a/b; else return 0; } }
程式總體結構說明:由主類jisuan和子類jiusuan組成
模組說明:檔案輸出和四則運算計算器的生成
目前程式設計的存在的困難和問題:
A:只能實現簡單的 四則運算檔,而且只要數比較打,就算結果正確也顯示不足;
B:出現異常要進行處理;單獨解決除數為0;
C :在編寫程式時將演算法和結構體還不能正確使用。
程式設計練習2:採用泛型程式設計技術改進實驗九程式設計練習2,使之可處理實數四則運算,其他要求不變。
import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class Suanshu { public static void main(String[] args) { Scanner in = new Scanner(System.in); Suanshu ss = new Suanshu(); PrintWriter out = null; try { out = new PrintWriter("test.txt"); } catch (FileNotFoundException e) { System.out.println("資料夾輸出失敗"); e.printStackTrace(); } 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 m; Random rand = new Random(); m = (int) rand.nextInt(4) + 1; System.out.println("隨機生成的四則運算型別:" + m); switch (m) { case 1: a = b + (int) Math.round(Math.random() * 100); 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 c0 = in.nextInt(); out.println(a + "/" + b + "=" + c0); if (c0 == ss.chufa(a, b)) { sum += 10; System.out.println("right!"); } else { System.out.println("error!"); } break; case 2: System.out.println(i + " " + a + "*" + b + "="); int c = in.nextInt(); out.println(a + "*" + b + "=" + c); if (c == ss.chengfa(a, b)) { sum += 10; System.out.println("回答正確!"); } else { System.out.println("回答錯誤!"); } break; case 3: System.out.println(i + " " + a + "+" + b + "="); int c1 = in.nextInt(); out.println(a + "+" + b + "=" + c1); if (c1 == ss.jiafa(a, b)) { sum += 10; System.out.println("回答正確!"); } else { System.out.println("回答錯誤!"); } break; case 4: 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 == ss.jiafa(a, b)) { sum += 10; System.out.println("回答正確!"); } else { System.out.println("回答錯誤!"); } break; } } System.out.println("最後得分" + sum); out.println("最後得分" + sum); out.close(); } private int jiafa(int a, int b) { // TODO Auto-generated method stub return 0; } private int chengfa(int a, int b) { // TODO Auto-generated method stub return 0; } private int chufa(int a, int b) { // TODO Auto-generated method stub return 0; } }
public class Suanshu<T> { private T a; private T b; public Suanshu() { a = null; b = null; } public Suanshu(T a, T b) { this.a = a; this.b = b; } public int jiafa(int a,int b) { return a + b; } public int jianfa(int a, int b) { return a - b; } public int chengfa(int a, int b) { return a * b; } public int chufa(int a, int b) { if (b != 0 && a%b==0) return a / b; else return 0; } }
執行結果:
實驗總結:這一章學習第九章類泛型程式設計,主要學習瞭如何定義簡單泛型類,是用Pair類引入一個型別變數T,用<>,放在類名的後面,泛型類可以有多個泛型變數以及萬用字元胡型別,有帶有上界和下界,分別是?extends type,?super type等基礎知識,學習泛型程式設計是編寫的程式碼可以被很多不同的物件所重用,程式設計師必掌握的技術,因此,之前也接觸到了ArrayList類,泛型程式設計是用繼承實現的,總而言之,將這幾周學過的知識相結合運用到編寫程式碼才是一種提升能力,自己還需要不斷練習。