1. 程式人生 > >楊玲 201771010133《面向物件程式設計(java)》第十週學習總結

楊玲 201771010133《面向物件程式設計(java)》第十週學習總結

《面向物件程式設計(java)》第十週學習總結

第一部分:理論知識學習部分

   第八章    泛型程式設計

一、泛型程式設計的定義

1、JDK 5.0 中增加的泛型型別,是Java 語言中型別安全的一次重要改進。

2、 泛型:也稱引數化型別(parameterized type),就是在定義類、介面和方法時,通過型別引數指示將要處理的物件型別。(如ArrayList類)

3、泛型程式設計(Generic programming):編寫程式碼可以被很多不同型別的物件所重用。

4、一個泛型類(generic class)就是具有一個或多個型別變數的類,即建立用型別作為引數的類。

如一個泛型類定義格式如下:class Generics<K,V>其中的K和V是類中的可變型別引數。

5、Pair類引入了一個型別變數T,用尖括號(<>)括起來,並放在類名的後面。

6、 泛型類可以有多個型別變數。例如:public class Pair<T, U> { … }

7、 類定義中的型別變數用於指定方法的返回型別以及域、區域性變數的型別。

二、泛型方法的宣告

1、 泛型方法

(1) 除了泛型類外,還可以只單獨定義一個方法作為泛型方法,用於指定方法引數或者返回值為泛型型別,留待方法呼叫時確定。

(2) 泛型方法可以宣告在泛型類中,也可以宣告在普通類中。

第二部分:實驗部分

1.實驗名稱:實驗十  泛型程式設計技術

2.實驗目的與要求

(1) 理解泛型概念;

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

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

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

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

3.實驗內容和步驟

實驗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    private T first;
10    private T second;
11 
12    public Pair() { first = null; second = null; }
13    public Pair(T first, T second) { this.first = first;  this.second = second; }
14 
15    public T getFirst() { return first; }
16    public T getSecond() { return second; }
17 
18    public void setFirst(T newValue) { first = newValue; }
19    public void setSecond(T newValue) { second = newValue; }
20 }
 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);
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++)//for迴圈語句
31       {
32          if (min.compareTo(a[i]) > 0) min = a[i];
33          if (max.compareTo(a[i]) < 0) max = a[i];
34       }
35       return new Pair<>(min, max);
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    private T first;
10    private T second;
11 
12    public Pair() { first = null; second = null; }
13    public Pair(T first, T second) { this.first = first;  this.second = second; }
14 
15    public T getFirst() { return first; }
16    public T getSecond() { return second; }
17 
18    public void setFirst(T newValue) { first = newValue; }
19    public void setSecond(T newValue) { second = newValue; }
20 }

 

 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);
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    public static <T extends Comparable> Pair<T> minmax(T[] a) //定義泛型變數的上界,extends關鍵字所宣告的上界既可以是一個類,也可以是一個介面;
35    {
36       if (a == null || a.length == 0) return null;//條件判斷語句
37       T min = a[0];
38       T max = a[0];
39       for (int i = 1; i < a.length; i++)//for迴圈語句
40       {
41          if (min.compareTo(a[i]) > 0) min = a[i];
42          if (max.compareTo(a[i]) < 0) max = a[i];
43       }
44       return new Pair<>(min, max);
45    }
46 }

 

執行結果如下:

 

測試程式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 public class Manager extends Employee
 4 {  
 5    private double bonus;
 6 
 7    /**
 8       @param name the employee's name
 9       @param salary the salary
10       @param year the hire year
11       @param month the hire month
12       @param day the hire day
13    */
14    public Manager(String name, double salary, int year, int month, int day)
15    {  
16       super(name, salary, year, month, day);
17       bonus = 0;
18    }
19 
20    public double getSalary()
21    { 
22       double baseSalary = super.getSalary();
23       return baseSalary + bonus;
24    }
25 
26    public void setBonus(double b)
27    {  
28       bonus = b;
29    }
30 
31    public double getBonus()
32    {  
33       return bonus;
34    }
35 }

 

 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    private T first;
10    private T second;
11 
12    public Pair() { first = null; second = null; }
13    public Pair(T first, T second) { this.first = first;  this.second = second; }
14 
15    public T getFirst() { return first; }
16    public T getSecond() { return second; }
17 
18    public void setFirst(T newValue) { first = newValue; }
19    public void setSecond(T newValue) { second = newValue; }
20 }

 

 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    public static void printBuddies(Pair<? extends Employee> p)//表示帶有上界
30    {
31       Employee first = p.getFirst();
32       Employee second = p.getSecond();
33       System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
34    }
35 
36    public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)//定義泛型變數的下界,通過使用super關鍵字可以固定泛型引數的型別為某種型別或者其超類
37    {
38       if (a.length == 0) return;
39       Manager min = a[0];
40       Manager max = a[0];
41       for (int i = 1; i < a.length; i++)
42       {
43          if (min.getBonus() > a[i].getBonus()) min = a[i];
44          if (max.getBonus() < a[i].getBonus()) max = a[i];
45       }
46       result.setFirst(min);
47       result.setSecond(max);
48    }
49 
50    public static void maxminBonus(Manager[] a, Pair<? super Manager> result)//表示帶有下界
51    {
52       minmaxBonus(a, result);
53       PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
54    }
55    // Can't write public static <T super manager> ...
56 }
57 
58 class PairAlg
59 {
60    public static boolean hasNulls(Pair<?> p)//"?"----型別變數的萬用字元,表示任何型別
61    {
62       return p.getFirst() == null || p.getSecond() == null;
63    }
64 
65    public static void swap(Pair<?> p) { swapHelper(p); }//無限定萬用字元,可以用任意Object物件呼叫原始的Pair類的setObject方法。
66 
67    public static <T> void swapHelper(Pair<T> p)
68    {
69       T t = p.getFirst();
70       p.setFirst(p.getSecond());
71       p.setSecond(t);
72    }
73 }

 執行結果如下:

 

實驗2:程式設計練習:

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

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

1、程式總體結構說明:

   主類Main  子類Person

2、模組說明

(1)Main

  • 檔案資訊的查詢
  • 根據實驗要求對檔案資訊進行選擇性讀取

(2) Person

  •  對讀取的資訊進行相應的、具體的處理  

3、目前程式設計存在的困難與問題:       由整體的框架構想到實際程式碼的實驗還有很多的路要走

4、程式具體模組展示如下:

  1 import java.io.BufferedReader;
  2 import java.io.File;
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.io.IOException;
  6 import java.io.InputStreamReader;
  7 import java.util.ArrayList;
  8 import java.util.Arrays;
  9 import java.util.Collections;
 10 import java.util.Scanner;
 11 
 12 public class Main{
 13     private static ArrayList<Person> Personlist;
 14     public static void main(String[] args) {
 15         Personlist = new ArrayList<>();
 16         Scanner scanner = new Scanner(System.in);
 17         File file = new File("D:\\身份證號.txt");
 18         try {
 19             FileInputStream fis = new FileInputStream(file);
 20             BufferedReader in = new BufferedReader(new InputStreamReader(fis));
 21             String temp = null;
 22             while ((temp = in.readLine()) != null) {
 23                 
 24                 Scanner linescanner = new Scanner(temp);
 25                 
 26                 linescanner.useDelimiter(" ");    
 27                 String name = linescanner.next();
 28                 String ID = linescanner.next();
 29                 String sex = linescanner.next();
 30                 String age = linescanner.next();
 31                 String place =linescanner.nextLine();
 32                 Person Person = new Person();
 33                 Person.setname(name);
 34                 Person.setID(ID);
 35                 Person.setsex(sex);
 36                 int a = Integer.parseInt(age);
 37                 Person.setage(a);
 38                 Person.setbirthplace(place);
 39                 Personlist.add(Person);
 40 
 41             }
 42         } catch (FileNotFoundException e) {
 43             System.out.println("查詢不到資訊");
 44             e.printStackTrace();
 45         } catch (IOException e) {
 46             System.out.println("資訊讀取有誤");
 47             e.printStackTrace();
 48         }
 49         boolean isTrue = true;
 50         while (isTrue) {
 51             System.out.println("————————————————————————————————————————");
 52             System.out.println("1:按姓名字典序輸出人員資訊");
 53             System.out.println("2:查詢最大年齡與最小年齡人員資訊");
 54             System.out.println("3:按省份找同鄉");
 55             System.out.println("4:輸入你的年齡,查詢年齡與你最近人的資訊");
 56             System.out.println("5:exit");
 57             int nextInt = scanner.nextInt();
 58             switch (nextInt) {
 59             case 1:
 60                 Collections.sort(Personlist);
 61                 System.out.println(Personlist.toString());
 62                 break;
 63             case 2:
 64                 
 65                 int max=0,min=100;int j,k1 = 0,k2=0;
 66                 for(int i=1;i<Personlist.size();i++)
 67                 {
 68                     j=Personlist.get(i).getage();
 69                    if(j>max)
 70                    {
 71                        max=j; 
 72                        k1=i;
 73                    }
 74                    if(j<min)
 75                    {
 76                        min=j; 
 77                        k2=i;
 78                    }
 79 
 80                 }  
 81                 System.out.println("年齡最大:"+Personlist.get(k1));
 82                 System.out.println("年齡最小:"+Personlist.get(k2));
 83                 break;
 84             case 3:
 85                 System.out.println("place?");
 86                 String find = scanner.next();        
 87                 String place=find.substring(0,3);
 88                 String place2=find.substring(0,3);
 89                 for (int i = 0; i <Personlist.size(); i++) 
 90                 {
 91                     if(Personlist.get(i).getbirthplace().substring(1,4).equals(place)) 
 92                         System.out.println("maybe is      "+Personlist.get(i));
 93 
 94                 } 
 95 
 96                 break;
 97             case 4:
 98                 System.out.println("年齡:");
 99                 int yourage = scanner.nextInt();
100                 int near=agenear(yourage);
101                 int d_value=yourage-Personlist.get(near).getage();
102                 System.out.println(""+Personlist.get(near));
103            /*     for (int i = 0; i < Personlist.size(); i++)
104                 {
105                     int p=Personlist.get(i).getage()-yourage;
106                     if(p<0) p=-p;
107                     if(p==d_value) System.out.println(Personlist.get(i));
108                 }   */
109                 break;
110             case 5:
111            isTrue = false;
112            System.out.println("退出程式!");
113                 break;
114             default:
115                 System.out.println("輸入有誤");
116             }
117         }
118     }
119     public static int agenear(int age) {
120      
121        int j=0,min=53,d_value=0,k=0;
122         for (int i = 0; i < Personlist.size(); i++)
123         {
124             d_value=Personlist.get(i).getage()-age;
125             if(d_value<0) d_value=-d_value; 
126             if (d_value<min) 
127             {
128                min=d_value;
129                k=i;
130             }
131 
132          }    return k;
133         
134      }
135 
136  
137 }

 

 1 public class Person implements Comparable<Person> {
 2 private String name;
 3 private String ID;
 4 private int age;
 5 private String sex;
 6 private String birthplace;
 7 
 8 public String getname() {
 9 return name;
10 }
11 public void setname(String name) {
12 this.name = name;
13 }
14 public String getID() {
15 return ID;
16 }
17 public void setID(String ID) {
18 this.ID= ID;
19 }
20 public int getage() {
21 
22 return age;
23 }
24 public void setage(int age) {
25     // int a = Integer.parseInt(age);
26 this.age= age;
27 }
28 public String getsex() {
29 return sex;
30 }
31 public void setsex(String sex) {
32 this.sex= sex;
33 }
34 public String getbirthplace() {
35 return birthplace;
36 }
37 public void setbirthplace(String birthplace) {
38 this.birthplace= birthplace;
39 }
40 
41 public int compareTo(Person o) {
42    return this.name.compareTo(o.getname());
43 
44 }
45 
46 public String toString() {
47     return  name+"\t"+sex+"\t"+age+"\t"+ID+"\t"+birthplace+"\n";
48 
49 }
50 
51 
52 
53 }

 

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

 

1、程式總體結構說明:

 

   主類Demo  子類Counter

 

2、模組說明

 

(1)Demo

 

  • 十道四則運算練習題的生成
  • 輸入答案的正誤判斷
  • 檔案的生成

 

(2)Counter

 

  •  四則運算的具體計算

 

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

    text檔案的輸出存在問題

4、程式具體模組展示如下:

 1 import java.io.FileNotFoundException;
 2 import java.io.PrintWriter;
 3 import java.util.Scanner;
 4 
 5 /*
 6  * 該程式用來隨機生成0到100以內的加減乘除題
 7  */
 8 public class Demo {
 9     public static  void main(String[] args) {
10         // 使用者的答案要從鍵盤輸入,因此需要一個鍵盤輸入流
11         Scanner in = new Scanner(System.in);
12         Counter counter=new Counter();
13         PrintWriter out = null;
14         try {
15             out = new PrintWriter("text.txt");
16         } catch (FileNotFoundException e) {
17             // TODO Auto-generated catch block
18             e.printStackTrace();
19         }
20         // 定義一個變數用來統計得分
21         int sum = 0;
22         int k=0;
23         // 通過迴圈生成10道題
24         for (int i = 0; i < 10; i++) {
25 
26             // 隨機生成兩個100以內的隨機數作加減乘除
27             int a = (int) Math.round(Math.random() * 100);
28             int b = (int) Math.round(Math.random() * 100);
29             int d = (int) Math.round(Math.random() * 3);
30             
31             switch (d){
32             
33             case 0: 
34               if(a%b == 0) {
35               System.out.println(a + "/" + b + "=");
36               break;
37               }
38               //int c = in.nextInt();
39               //out.println(a + "/" + b + "="+c);
40             case 1:
41               System.out.println(a + "*" + b + "=");
42               //int c1 = in.nextInt();
43               //out.println(a + "*" + b + "="+c1);
44               break;
45             case 2:
46               System.out.println(a + "+" + b + "=");
47               //int c2 = in.nextInt();
48               //out.println(a + "+" + b + "="+c2);
49               break;
50             case 3:
51             if(a>b) {
52             System.out.println(a + "-" + b + "=");
53             break;
54             }
55             //int c3 = in.nextInt();
56             //out.println(a + "-" + b + "="+c3);
57             
58             }        
59 
60             // 定義一個整數用來接收使用者輸入的答案
61             double c = in.nextDouble();
62             
63             // 判斷使用者輸入的答案是否正確,正確給10分,錯誤不給分
64             if (c == a / b | c == a * b | c == a + b | c == a - b) {
65                 sum += 10;
66                 System.out.println("恭喜答案正確");
67             }
68             else {
69                 System.out.println("抱歉,答案錯誤");
70             
71             }
72             out.println(a + "/" + b + "="+c );
73             out.println(a + "*" + b + "="+c);
74             out.println(a + "+" + b + "="+c);
75             out.println(a + "-" + b + "="+c);
76         
77         }
78         //輸出使用者的成績
79         System.out.println("你的得分為"+sum);
80         
81         out.println("成績:"+sum);
82         out.close();
83     }
84     }
public class Counter {
       private int a;
       private int b;
        public int  add(int a,int b)
        {
            return a+b;
        }
        public int   reduce(int a,int b)
        {
            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;
        }

}

 

 

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

改進後的程式如下:

 

 1 import java.io.FileNotFoundException;
 2 import java.io.PrintWriter;
 3 import java.util.Scanner;
 4 
 5 /*
 6  * 該程式用來隨機生成0到100以內的加減乘除題
 7  */
 8 public class Demo {
 9     public static  void main(String[] args) {
10         // 使用者的答案要從鍵盤輸入,因此需要一個鍵盤輸入流
11         Scanner in = new Scanner(System.in);
12         Counter counter=new Counter();
13         PrintWriter out = null;
14         try {
15             out = new PrintWriter("text.txt");
16         } catch (FileNotFoundException e) {
17             // TODO Auto-generated catch block
18             e.printStackTrace();
19         }
20         // 定義一個變數用來統計得分
21         int sum = 0;
22         int k=0;
23         // 通過迴圈生成10道題
24         for (int i = 0; i < 10; i++) {
25 
26             // 隨機生成兩個100以內的隨機數作加減乘除
27             int a = (int) Math.round(Math.random() * 100);
28             int b = (int) Math.round(Math.random() * 100);
29             int d = (int) Math.round(Math.random() * 3);
30             
31             switch (d){
32             
33             case 0: 
34               if(a%b == 0) {
35               System.out.println(a + "/" + b + "=");
36               break;
37               }
38               //int c = in.nextInt();
39               //out.println(a + "/" + b + "="+c);
40             case 1:
41               System.out.println(a + "*" + b + "=");
42               //int c1 = in.nextInt();
43               //out.println(a + "*" + b + "="+c1);
44               break;
45             case 2:
46               System.out.println(a + "+" + b + "=");
47               //int c2 = in.nextInt();
48               //out.println(a + "+" + b + "="+c2);
49               break;
50             case 3:
51             if(a>b) {
52             System.out.println(a + "-" + b + "=");
53             break;
54             }
55             //int c3 = in.nextInt();
56             //out.println(a + "-" + b + "="+c3);
57             
58             }        
59 
60             // 定義一個整數用來接收使用者輸入的答案
61             double c = in.nextDouble();
62             
63             // 判斷使用者輸入的答案是否正確,正確給10分,錯誤不給分
64             if (c == a / b | c == a * b | c == a + b | c == a - b) {
65                 sum += 10;
66                 System.out.println("恭喜答案正確");
67             }
68             else {
69                 System.out.println("抱歉,答案錯誤");
70             
71             }
72             out.println(a + "/" + b + "="+c );
73             out.println(a + "*" + b + "="+c);
74             out.println(a + "+" + b + "="+c);
75             out.println(a + "-" + b + "="+c);
76         
77         }
78         //輸出使用者的成績
79         System.out.println("你的得分為"+sum);
80         
81         out.println("成績:"+sum);
82         out.close();
83     }
84     }

 

 

 

 

 

 

4. 實驗總結:

         通過本次實驗我理解了泛型的概念;掌握了泛型類的定義與使用; 掌握了泛型方法的宣告與使用; 掌握了泛型介面的定義與實現;瞭解了泛型程式設計和它的用途。