1. 程式人生 > >201771010135 楊蓉慶《面對物件程式設計(java)》第十週學習總結

201771010135 楊蓉慶《面對物件程式設計(java)》第十週學習總結

1、實驗目的與要求

(1) 理解泛型概念;

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

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

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

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

一、理論知識

泛型類的定義:

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

(2)一個泛型類(generic class)就是具有一個或多個型別變數的類,即建立用型別作為引數的類。
如一個泛型類定義格式如下:class Generics<K,V>

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

泛型變數的限定:

(1)extends關鍵字所宣告的上界既可以是一個類,也可以是一個介面;

(2)<T extends Bounding Type>表示T應該是繫結型別的子型別。

泛型變數下界的說明:
– 通過使用super關鍵字可以固定泛型引數的型別為某種
型別或者其超類
– 當程式希望為一個方法的引數限定型別時,通常可以使
用下限萬用字元

泛型類的約束與侷限性:

不能用基本型別例項化型別引數
執行時型別查詢只適用於原始型別
不能丟擲也不能捕獲泛型類例項
引數化型別的陣列不合法不能例項化型別變數
泛型類的靜態上下文中型別變數無效
注意擦除後的衝突

萬用字元型別:

“?”符號表明引數的型別可以是任何一種型別,它和引數T的含義是有區別的。T表示一種未知型別,而“?”表示任何一種型別.

這種萬用字元一般有以下三種用法:
單獨的?,用於表示任何型別。
? extends type,表示帶有上界。
? super type,表示帶有下界。

二、實驗內容和步驟

實驗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;//use the type variable 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" };//定義常量
      Pair<String> mm = ArrayAlg.minmax(words);//類名呼叫方法名
      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)//泛型類例項化
   {
      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];//compareTo比較方法
         if (max.compareTo(a[i]) < 0) max = a[i];
      }
      return new Pair<>(min, max);//例項化後的呼叫物件
   }
}

結果如下:

測試程式2:

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

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

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

package pair1;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T>//Pair類引入了一個型別變數T 
{
   private T first;//use the type variable
   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 pair2;

import java.time.*;

/**
 * @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);//例項化一個LocalDat類
      System.out.println("min = " + mm.getFirst());
      System.out.println("max = " + mm.getSecond());//得到min、max
   }
}

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) //將T限制為實現Comparable介面的類
   {
      if (a == null || a.length == 0) return null;
      T min = a[0];
      T max = a[0];
      for (int i = 1; i < a.length; i++)//compareTo方法
      {
         if (min.compareTo(a[i]) > 0) min = a[i];
         if (max.compareTo(a[i]) < 0) max = a[i];
      }
      return new Pair<>(min, max);//返回新的pair類
   }
}

結果如下:

測試程式3:

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

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

package pair3;

/**
 * @version 1.01 2012-01-26
 * @author Cay Horstmann
 */
public class PairTest3
{
   public static void main(String[] args)
   {
       //定義Manager類
      Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
      Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
      Pair<Manager> buddies = new Pair<>(ceo, cfo);      
      printBuddies(buddies);

      ceo.setBonus(1000000);
      cfo.setBonus(500000);
      Manager[] managers = { ceo, cfo };

      Pair<Employee> result = new Pair<>();//程式呼叫泛型方法
      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)
   {
      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)
   //任何泛型Pair型別,它的型別引數是Manager的子類
   {
      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)//統配符限制為Manager的所有超型別
   {
      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); }
   //swap呼叫swapHelper
   public static <T> void swapHelper(Pair<T> p)
   {
      T t = p.getFirst();
      p.setFirst(p.getSecond());
      p.setSecond(t);
   }
}

Employee:

package pair3;

import java.time.*;

public class Employee
//構造一個Employee類
{  
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;//this直接引用
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }
    //訪問器方法
   public String getName()
   {
      return name;
   }

   public double getSalary()
   {  
      return salary;
   }

   public LocalDate getHireDay()
   {  
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {  
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

Manager:

package pair3;

public class Manager extends Employee//Manager類的父類是Employee類
{  
   private double bonus;

   /**
      @param name the employee's name
      @param salary the salary
      @param year the hire year
      @param month the hire month
      @param day the hire day
   */
   public Manager(String name, double salary, int year, int month, int day)
   {  
      super(name, salary, year, month, day);
      bonus = 0;
   }

   public double getSalary()
   { 
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }

   public void setBonus(double b)
   {  
      bonus = b;
   }

   public double getBonus()
   {  
      return bonus;
   }
}l

 結果如下:

實驗2程式設計練習:

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

  •  實驗九程式設計練習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;

@SuppressWarnings("unused")
public class Main{
    private static ArrayList<Person> Personlist;
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        Personlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("E:\\新建資料夾\\身份證號.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();
                Person Person = new Person();
                Person.setname(name);
                Person.setID(ID);
                Person.setsex(sex);
                int a = Integer.parseInt(age);
                Person.setage(a);
                Person.setbirthplace(place);
                Personlist.add(Person);

            }
        } 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(Personlist);
                System.out.println(Personlist.toString());
                break;
            case 2:
                
                int max=0,min=100;int j,k1 = 0,k2=0;
                for(int i=1;i<Personlist.size();i++)
                {
                    j=Personlist.get(i).getage();
                   if(j>max)
                   {
                       max=j; 
                       k1=i;
                   }
                   if(j<min)
                   {
                       min=j; 
                       k2=i;
                   }

                }  
                System.out.println("年齡最大:"+Personlist.get(k1));
                System.out.println("年齡最小:"+Personlist.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 <Personlist.size(); i++) 
                {
                    if(Personlist.get(i).getbirthplace().substring(1,4).equals(place)) 
                        System.out.println(""+Personlist.get(i));

                } 

                break;
            case 4:
                System.out.println("年齡:");
                int yourage = scanner.nextInt();
                int near=agenear(yourage);
                int d_value=yourage-Personlist.get(near).getage();
                System.out.println(""+Personlist.get(near));
           /*     for (int i = 0; i < Personlist.size(); i++)
                {
                    int p=Personlist.get(i).getage()-yourage;
                    if(p<0) p=-p;
                    if(p==d_value) System.out.println(Personlist.get(i));
                }   */
                break;
            case 5:
           isTrue = false;
           System.out.println("退出程式!");
                break;
            default:
                System.out.println("輸入有誤");            }
        }
    }
    public static int agenear(int age) {
     
       int j=0,min=53,d_value=0,k=0;
        for (int i = 0; i < Personlist.size(); i++)
        {
            d_value=Personlist.get(i).getage()-age;
            if(d_value<0) d_value=-d_value; 
            if (d_value<min) 
            {
               min=d_value;
               k=i;
            }

         }    return k;
        }
}
Main

程式總體結構:總體分為Main類和Person類

 

Main類:

1、將人員身份資訊匯入程式碼中

2、編輯了查詢人員資訊的方法

3、分5個case來分別說年齡大小、同鄉等訊息

Person類:

package ID;
public class Person implements Comparable<Person> {
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(Person o) {
   return this.name.compareTo(o.getname());

}

public String toString() {
    return  name+"\t"+sex+"\t"+age+"\t"+ID+"\t"+birthplace+"\n";

}
}
Person

對各個小模組進行具體的分析

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

1、編寫時基礎錯誤還是很多

2、Main類和Person類的變數名有時不能統一

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

程式總體結構:Demo主類和Counter類

模組說明:Demo主類

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;


public class Demo {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        jf counter=new jf();
        PrintWriter out = null;
        try {
            out = new PrintWriter("text.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            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= (int) Math.round(Math.random() * 3);

            
           switch(m)
           {
           case 0:
               System.out.println(i+": "+a+"/"+b+"=");
               
               while(b==0){  b = (int) Math.round(Math.random() * 100); }
               
            int c0 = in.nextInt();
            out.println(a+"/"+b+"="+c0);
            if (c0 == jf.division(a, b)) {
                sum += 10;
                System.out.println("恭喜答案正確");
            }
            else {
                System.out.println("抱歉,答案錯誤");
            }
            
            break;
            
           case 1:
               System.out.println(i+": "+a+"*"+b+"=");
               int c = in.nextInt();
               out.println(a+"*"+b+"="+c);
               if (c == counter.multiplication(a, b)) {
                   sum += 10;
                   System.out.println("恭喜答案正確");
               }
               else {
                   System.out.println("抱歉,答案錯誤");
               }
               break;
           case 2:
               System.out.println(i+": "+a+"+"+b+"=");
               int c1 = in.nextInt();
               out.println(a+"+"+b+"="+c1);
               if (c1 == counter.add(a, b)) {
                   sum += 10;
                   System.out.println("恭喜答案正確");
               }
               else {
                   System.out.println("抱歉,答案錯誤");
               }
               
               break ;
           case 3:
               System.out.println(i+": "+a+"-"+b+"=");
               int c2 = in.nextInt();
               out.println(a+"-"+b+"="+c2);
               if (c2 == counter.reduce(a, b)) {
                   sum += 10;
                   System.out.println("恭喜答案正確");
               }
               else {
                   System.out.println("抱歉,答案錯誤");
               }
               break ;

               } 
    
          }
        System.out.println("成績"+sum);
        out.println("成績:"+sum);
         out.close();

         
    }
    }
Demo

1、判斷答案的正確性程式碼

2、檔案的讀取

3、四則運算程式碼的具體呈現

Counter類

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;
    }

    
}
Counter

四則運算的計算過程及返回值

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

1、數值過大,無法口算

2、運算複雜,不符合基礎運算難度

 

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

package C;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Suanfa counter = new Suanfa();
        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);
                    }
              //若生成的除法式子必須能整除,且滿足分母為0的條件,則a一定要大於b,且a模b的結果要為0。
                System.out.println(i + ": " + a + "/" + b + "=");
                int c0 = in.nextInt();
                out.println(a + "/" + b + "=" + c0);
                if (c0 == counter.d(a, b)) {
                    sum += 10;
                    System.out.println("正確!");
                } else {
                    System.out.println("錯誤!");
                }
 break;

            case 2:
                System.out.println(i + ": " + a + "*" + b + "=");
                int c = in.nextInt();
                out.println(a + "*" + b + "=" + c);
                if (c == counter.m(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 == counter.add(a, b)) {
                    sum += 10;
                    System.out.println("正確!");
                } else {
                    System.out.println("錯誤!");
                }
                break;
            case 4:
                while (a < b) {
                    b = (int) Math.round(Math.random() * 100);
                }
              //因為不能產生運算結果為負數的減法式子,所以a一定要大於b。若a<b,則重新生成b。
                System.out.println(i + ": " + a + "-" + b + "=");
                int c2 = in.nextInt();
                out.println(a + "-" + b + "=" + c2);
                if (c2 == counter.r(a, b)) {
                    sum += 10;
                    System.out.println("正確!");
                } else {
                    System.out.println("錯誤!");
                }
                break;
            }
        }
        System.out.println("成績" + sum);
        out.println("成績:" + sum);
        out.close();
    }
}
Main
package C;
public class Suanfa<T> {
    private T a;
    private T b;
   public int add(int a,int b) {
        return a + b;
    }

    public int r(int a, int b) {
        return a - b;
    }

    public int m(int a, int b) {
        return a * b;
    }

    public int d(int a, int b) {
        if (b != 0 && a%b==0)
            return a / b;
        else
            return 0;
    }
}
Suanfa

 結果如下:

三、總結如下:

本章我們學習了泛型程式設計技術,首先理解了泛型概念,掌握泛型類的定義與使用,泛型方法的宣告與使用,最後感覺瞭解泛型程式設計及其用途,在驗證實驗中,通過對程式碼的解讀,更深的學習了泛型程式<T>的使用,還複習了實驗九的兩個程式設計題目,感覺依舊存在些小問題,在接下來的實驗中要更好的解決,程式設計實驗中,在實驗九的四則運算基礎上,加入了本章泛型程式的概念,雖然不是很熟練,但還是勉強做出來了。