1. 程式人生 > >201771010102 常惠琢《2018面向物件程式設計(Java)》第10周學習總結

201771010102 常惠琢《2018面向物件程式設計(Java)》第10周學習總結

實驗十  泛型程式設計技術

實驗時間 2018-11-1

1、實驗目的與要求

(1) 理解泛型概念;

(2) 掌握泛型類的定義與使用;

(3) 掌握泛型方法的宣告與使用;

(4) 掌握泛型介面的定義與實現;

(5)瞭解泛型程式設計,理解其用途。

2、實驗內容和步驟

實驗1: 匯入第8章示例程式,測試程式並進行程式碼註釋。

測試程式1:

l 編輯、除錯、執行教材311、312頁 程式碼,結合程式執行結果理解程式;

l 在泛型類定義及使用程式碼處添加註釋;

l 掌握泛型類的定義及使用。 

 1 package pair1;
 2 
 3 /**
 4  * @version 1.00 2004-05-10
 5  * @author Cay Horstmann
 6  */
 7 public class Pair<T> //Pair引入一個型別變數T
 8 {
 9    //類定義中的型別變數指定方法的返回型別以及域和區域性變數的型別
10    private T first;
11    private T second;
12 
13    public Pair() { first = null; second = null; }
14    public Pair(T first, T second) { this
.first = first; this.second = second; } 15 16 public T getFirst() { return first; } 17 public T getSecond() { return second; } 18 19 public void setFirst(T newValue) { first = newValue; } 20 public void setSecond(T newValue) { second = newValue; } 21 }
 1 package pair1;
 2 
 3 /**
4 * @version 1.01 2012-01-26 5 * @author Cay Horstmann 6 */ 7 public class PairTest1 8 { 9 public static void main(String[] args) 10 { 11 String[] words = { "Mary", "had", "a", "little", "lamb" }; 12 Pair<String> mm = ArrayAlg.minmax(words);//mm儲存minmax物件的返回值 13 System.out.println("min = " + mm.getFirst()); 14 System.out.println("max = " + mm.getSecond()); 15 } 16 } 17 18 class ArrayAlg 19 { 20 /** 21 * Gets the minimum and maximum of an array of strings. 22 * @param a an array of strings 23 * @return a pair with the min and max value, or null if a is null or empty 24 *///版權、引數宣告 25 public static Pair<String> minmax(String[] a)//用具體的型別替換型別變數例項化泛型型別 26 { 27 if (a == null || a.length == 0) return null; 28 String min = a[0]; 29 String max = a[0]; 30 for (int i = 1; i < a.length; i++)//a.length指陣列的屬性值 31 { 32 if (min.compareTo(a[i]) > 0) min = a[i];//比較同時儲存最大值和最小值 33 if (max.compareTo(a[i]) < 0) max = a[i];//compareTo方法可實現字串比較 34 } 35 return new Pair<>(min, max);//返回Pair<>帶引數的構造器 36 } 37 }

測試程式2:

l 編輯、除錯執行教材315頁 PairTest2,結合程式執行結果理解程式;

l 在泛型程式設計程式碼處新增相關注釋;

l 掌握泛型方法、泛型變數限定的定義及用途。

 1 package pair2;
 2 
 3 /**
 4  * @version 1.00 2004-05-10
 5  * @author Cay Horstmann
 6  */
 7 public class Pair<T> //Pair引入一個型別變數T
 8 {
 9    //類定義中的型別變數指定方法的返回型別以及域和區域性變數的型別
10    private T first;
11    private T second;
12 
13    public Pair() { first = null; second = null; }
14    public Pair(T first, T second) { this.first = first;  this.second = second; }
15 
16    public T getFirst() { return first; }
17    public T getSecond() { return second; }
18 
19    public void setFirst(T newValue) { first = newValue; }
20    public void setSecond(T newValue) { second = newValue; }
21 }
 1 package pair2;
 2 
 3 import java.time.*;
 4 
 5 /**
 6  * @version 1.02 2015-06-21
 7  * @author Cay Horstmann
 8  */
 9 public class PairTest2
10 {
11    public static void main(String[] args)
12    {
13       LocalDate[] birthdays = 
14          { 
15             LocalDate.of(1906, 12, 9), // G. Hopper
16             LocalDate.of(1815, 12, 10), // A. Lovelace
17             LocalDate.of(1903, 12, 3), // J. von Neumann
18             LocalDate.of(1910, 6, 22), // K. Zuse
19          };
20       Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);//mm儲存minmax物件的返回值
21       System.out.println("min = " + mm.getFirst());
22       System.out.println("max = " + mm.getSecond());
23    }
24 }
25 
26 class ArrayAlg
27 {
28    /**
29       Gets the minimum and maximum of an array of objects of type T.
30       @param a an array of objects of type T
31       @return a pair with the min and max value, or null if a is 
32       null or empty
33    */
34    //將T限制為實現了Comparable介面的類。  定義泛型變數的上界(泛型方法)
35    public static <T extends Comparable> Pair<T> minmax(T[] a) 
36    {
37       if (a == null || a.length == 0) return null;
38       T min = a[0];
39       T max = a[0];
40       for (int i = 1; i < a.length; i++)
41       {
42          if (min.compareTo(a[i]) > 0) min = a[i];
43          if (max.compareTo(a[i]) < 0) max = a[i];
44       }
45       return new Pair<>(min, max);//返回Pair<>帶引數的構造器
46    }
47 }

 

 

測試程式3:

l 用除錯執行教材335頁 PairTest3,結合程式執行結果理解程式;

l 瞭解萬用字元型別的定義及用途。

 1 package pair3;
 2 
 3 import java.time.*;
 4 
 5 public class Employee
 6 {  
 7    private String name;
 8    private double salary;
 9    private LocalDate hireDay;
10 
11    public Employee(String name, double salary, int year, int month, int day)
12    {
13       this.name = name;
14       this.salary = salary;
15       hireDay = LocalDate.of(year, month, day);
16    }
17 
18    public String getName()
19    {
20       return name;
21    }
22 
23    public double getSalary()
24    {  
25       return salary;
26    }
27 
28    public LocalDate getHireDay()
29    {  
30       return hireDay;
31    }
32 
33    public void raiseSalary(double byPercent)
34    {  
35       double raise = salary * byPercent / 100;
36       salary += raise;
37    }
38 }
 1 package pair3;
 2 
 3 import pair3.Employee;
 4 
 5 public class Manager extends Employee
 6 {  
 7    private double bonus;
 8 
 9    /**
10       @param name the employee's name
11       @param salary the salary
12       @param year the hire year
13       @param month the hire month
14       @param day the hire day
15    */
16    public Manager(String name, double salary, int year, int month, int day)
17    {  
18       super(name, salary, year, month, day);
19       bonus = 0;
20    }
21 
22    public double getSalary()
23    { 
24       double baseSalary = super.getSalary();
25       return baseSalary + bonus;
26    }
27 
28    public void setBonus(double b)
29    {  
30       bonus = b;
31    }
32 
33    public double getBonus()
34    {  
35       return bonus;
36    }
37 }
 1 package pair3;
 2 
 3 /**
 4  * @version 1.00 2004-05-10
 5  * @author Cay Horstmann
 6  */
 7 public class Pair<T> //Pair引入一個型別變數T
 8 {
 9    //類定義中的型別變數指定方法的返回型別以及域和區域性變數的型別
10    private T first;
11    private T second;
12 
13    public Pair() { first = null; second = null; }
14    public Pair(T first, T second) { this.first = first;  this.second = second; }
15 
16    public T getFirst() { return first; }
17    public T getSecond() { return second; }
18 
19    public void setFirst(T newValue) { first = newValue; }
20    public void setSecond(T newValue) { second = newValue; }
21 }
 1 package pair3;
 2 
 3 /**
 4  * @version 1.01 2012-01-26
 5  * @author Cay Horstmann
 6  */
 7 public class PairTest3
 8 {
 9    public static void main(String[] args)
10    {
11       Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
12       Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
13       Pair<Manager> buddies = new Pair<>(ceo, cfo);      
14       printBuddies(buddies);
15 
16       ceo.setBonus(1000000);
17       cfo.setBonus(500000);
18       Manager[] managers = { ceo, cfo };
19 
20       Pair<Employee> result = new Pair<>();
21       minmaxBonus(managers, result);
22       System.out.println("first: " + result.getFirst().getName() 
23          + ", second: " + result.getSecond().getName());
24       maxminBonus(managers, result);
25       System.out.println("first: " + result.getFirst().getName() 
26          + ", second: " + result.getSecond().getName());
27    }
28 
29    //定義泛型變數的下界 。
30    public static void printBuddies(Pair<? extends Employee> p)
31    {
32       Employee first = p.getFirst();
33       Employee second = p.getSecond();
34       System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
35    }
36  
37    //定義泛型變數的下界 。
38    public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
39    {
40       if (a.length == 0) return;
41       Manager min = a[0];
42       Manager max = a[0];
43       for (int i = 1; i < a.length; i++)
44       {
45          if (min.getBonus() > a[i].getBonus()) min = a[i];
46          if (max.getBonus() < a[i].getBonus()) max = a[i];
47       }
48       result.setFirst(min);
49       result.setSecond(max);
50    }
51    
52    //定義泛型變數的下界 。     “?"為下限萬用字元。
53    public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
54    {
55       minmaxBonus(a, result);
56       PairAlg.swapHelper(result); //OK——swapHelper捕獲萬用字元型別
57    }
58    // 無法寫入公共靜態<T super manager> ...
59 }
60 
61 class PairAlg
62 {
63    public static boolean hasNulls(Pair<?> p)
64    {
65       return p.getFirst() == null || p.getSecond() == null;
66    }
67 
68    public static void swap(Pair<?> p) { swapHelper(p); }
69 
70    public static <T> void swapHelper(Pair<T> p)
71    {
72       T t = p.getFirst();
73       p.setFirst(p.getSecond());
74       p.setSecond(t);
75    }
76 }

 

實驗2:程式設計練習:

程式設計練習1:實驗九程式設計題總結

l 實驗九程式設計練習1總結(從程式總體結構說明、目前程式設計存在的困難與問題三個方面闡述)。

程式總體結構:主類PairTest1和Pair<T>類

 目前程式設計存在的困難與問題:

         偶爾會存在讀檔案時,檔案路徑不正確,無法找到檔案的問題,還有會讀檔案,但是就是自己編寫有問題,要不就得百度,要不就查書,檢查問題的。

l 實驗九程式設計練習2總結(從程式總體結構說明、目前程式設計存在的困難與問題三個方面闡述)。

程式總體結構:主類PairTest2和Pair<T>類:

目前程式設計存在的困難與問題:

讀程式碼問題不大,但還是存在編寫程式的問題,我會通過多加練習慢慢提高。

程式設計練習2:採用泛型程式設計技術改進實驗九程式設計練習2,使之可處理實數四則運算,其他要求不變。

 

 1 import java.io.FileNotFoundException;
 2 import java.io.IOException;
 3 import java.io.PrintWriter;
 4 import java.util.Scanner;
 5 public class Fine {
 6 
 7     public static void main(String[] args) {
 8                 Scanner in = new Scanner(System.in);
 9                 Min min=new Min();
10                 PrintWriter out = null;
11                 try {
12                     out = new PrintWriter("test.txt");
13                     int sum = 0;
14                     for (int i = 1; i <=10; i++) {
15                         int a = (int) Math.round(Math.random() * 100);
16                         int b = (int) Math.round(Math.random() * 100);
17                         int menu = (int) Math.round(Math.random() * 3);
18                         switch (menu) {
19                         case 0:
20                             System.out.println(i+":"+a + "+" + b + "=");
21                             int c1 = in.nextInt();
22                             out.println(a + "+" + b + "=" + c1);
23                             if (c1 == (a + b)) {
24                                 sum += 10;
25                                 System.out.println("恭喜答案正確");
26                             } else {
27                                 System.out.println("抱歉,答案錯誤");
28                             }
29                             break;
30                         case 1:
31                             while (a < b) {
32                                 b = (int) Math.round(Math.random() * 100);
33                             }
34                             System.out.println(i+":"+a + "-" + b + "=");
35                             int c2 = in.nextInt();
36                             out.println(a + "-" + b + "=" + c2);
37                             if (c2 == (a - b)) {
38                                 sum += 10;
39                                 System.out.println("恭喜答案正確");
40                             } else {
41                                 System.out.println("抱歉,答案錯誤");
42                             }
43 
44                             break;
45                         case 2:
46                             System.out.println(i+":"+a + "*" + b + "=");
47                             int c3 = in.nextInt();
48                             out.println(a + "*" + b + "=" + c3);
49                             if (c3 == a * b) {
50                                 sum += 10;
51                                 System.out.println("恭喜答案正確");
52                             } else {
53                                 System.out.println("抱歉,答案錯誤");
54                             }
55 
56                             break;
57                         case 3:
58                              while(b == 0){
59                                     b = (int) Math.round(Math.random() * 100);
60                                 }
61                                 while(a % b != 0){
62                                     a = (int) Math.round(Math.random() * 100);
63                                     
64                                 }
65                             System.out.println(i+":"+a + "/" + b + "=");
66                             int c4 = in.nextInt();
67                             if (c4 == a / b) {
68                                 sum += 10;
69                                 System.out.println("恭喜,答案正確");
70                             } else {
71                                 System.out.println("抱歉,答案錯誤");
72                             }
73 
74                             break;
75                         }
76                     }
77                     System.out.println("你的得分為" + sum);
78                     out.println("你的得分為" + sum);
79                     out.close();
80                 } catch (FileNotFoundException e) {
81                     e.printStackTrace();
82                 }
83             }
84         }

 

 1 public class Min<T> {
 2     private T a;
 3     private T b;
 4     public Min() {
 5         a=null;
 6         b=null;
 7     }
 8     public Min(T a,T b) {
 9         this.a=a;
10         this.b=b;
11     }
12     public int count1(int a,int b) {
13         return a+b;
14     }
15     public int count2(int a,int b) {
16         return a-b;
17     }
18     public int count3(int a,int b) {
19         return a*b;
20     }
21     public int count4(int a,int b) {
22         return a/b;
23     }
24 }