1. 程式人生 > >201771010123汪慧和《面向物件程式設計Java》第十週實驗總結

201771010123汪慧和《面向物件程式設計Java》第十週實驗總結

一、理論部分

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

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

3、泛型方法:

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

b.泛型方法可以申明在泛型類中,也可以申明在普通類中。

4、定義泛型變數的上界

public class NumberGeneric< T extends Number>

a.上述宣告規定了NumberGeneric類所能處理的泛型變數型別需和Number有繼承關係;
b.extends關鍵字所宣告的上界既可以是一個類,也可以是一個介面。
5、<T extends Bounding Type>表示T應該是繫結型別的子型別。

6、一個型別變數或萬用字元可以有多個限定,限定型別用“&”分割。

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

8、Java中的陣列是協變的,但這一原理不適用於泛型型別。不允許這樣做的理由:避免破壞要提供型別的安全泛型。

9、泛型類可擴充套件或實現其它的泛型類。

10、萬用字元
a. “?”符號表明引數的型別可以是任何一種型別,它和引數T的含義是有區別的。T表示一種未知型別,而“?”表示任何一種型別。這種萬用字元一般有以下三種用法:
(1)單獨的?,用於表示任何型別。
(2)? extends type,表示帶有上界。
(3) ? super type,表示帶有下界。

11、無限定的萬用字元,例如,Pair<?>。Pair<?>與Pair的不同在於:可以用任意Object物件呼叫原始的Pair類的setObject方法。

二、實驗部分

1、實驗目的與要求

(1) 理解泛型概念;

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

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

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

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

2、實驗內容和步驟

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

測試程式1:

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

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

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

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);//通過類名呼叫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];//字串物件比較,通過ASCII碼比較
         if (max.compareTo(a[i]) < 0) max = a[i];
      }
      return new Pair<>(min, max);//泛型類作為返回值
   }
}
package pair1;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class 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; }
}

實驗結果如下:

測試程式2:

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

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

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

package pair2;

import java.time.*;

/**
 * @version 1.02 2015-06-21
 * @author Cay Horstmann
 */
public class PairTest2
{
   public static void main(String[] args)
   {
       //初始化LocalDate物件陣列
      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)//加了上界約束的泛型方法
   {
      if (a == null || a.length == 0) return null;
      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);
   }
}
package pair2;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class 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; }
}

實驗結果如下圖所示:

測試程式3:

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

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

package pair3;

/**
 * @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<>(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)
   {
      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)
   {
      minmaxBonus(a, result);
      PairAlg.swapHelper(result); //swapHelper捕獲萬用字元型別
   }
   // 不能寫公共靜態 <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)
   {
      T t = p.getFirst();
      p.setFirst(p.getSecond());
      p.setSecond(t);
   }
}
package pair3;

public class Manager extends 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;
   }
}
package pair3;

import java.time.*;

public class 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.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;
   }
}
package pair3;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class 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; }
}

實驗結果如下圖所示:

實驗2:程式設計練習:

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

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

程式總體結構說明:包括ID類和main類以及Comparable介面。

模組說明:ID類和main類

 

package IDcard;
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.Scanner;
import java.util.Collections;

public class ID {

    public static People findPeopleByname(String name) {
        People flag = null;
        for (People people : peoplelist) {
            if(people.getName().equals(name)) {
                flag = people;
            }
        }
        return flag;

    }

    public static People findPeopleByid(String id) {
        People flag = null;
        for (People people : peoplelist) {
            if(people.getnumber().equals(id)) {
                flag = people;
            }
        }
        return flag;

    }
     
    private static ArrayList<People> agenear(int yourage) {
        // TODO Auto-generated method stub
        int j=0,min=53,d_value=0,k = 0;
        ArrayList<People> plist = new ArrayList<People>();
        for (int i = 0; i < peoplelist.size(); i++) {
            d_value = peoplelist.get(i).getage() > yourage ? 
                    peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ;
            k = d_value < min ? i : k;
            min = d_value < min ? d_value : min;
        }
        for(People people : peoplelist) {
            if(people.getage() == peoplelist.get(k).getage()) {
                plist.add(people);
            }
        }
        return plist;
    }

    private static ArrayList<People> peoplelist; 
    
    public static void main(String[] args) {
        peoplelist = new ArrayList<People>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("D:\\身份證號.txt");
        try {
            FileInputStream files = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(files));
            String temp = null;
            while ((temp = in.readLine()) != null) {
                
                String[] information = temp.split("[ ]+");
                People people = new People();
                people.setName(information[0]);
                people.setnumber(information[1]);
                int A = Integer.parseInt(information[3]);
                people.setage(A);
                people.setsex(information[2]);
                for(int j = 4; j<information.length;j++) {
                    people.setplace(information[j]);
                }
                peoplelist.add(people);

            }
        } 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.輸入你的年齡,查詢身份證號.txt中年齡與你最近的人");
            System.out.println("   5.查詢人員中是否有你的同鄉");
            System.out.println("   6.退出");
            System.out.println("******************************************");
            int nextInt = scanner.nextInt();
            switch (nextInt) {
            case 1:
                Collections.sort(peoplelist);
                System.out.println(peoplelist.toString());
                break;
            case 2:
                int max=0;
                int j,k1 = 0;
                for(int i=1;i<peoplelist.size();i++)
                {
                    j = peoplelist.get(i).getage();
                   if(j>max)
                   {
                       max = j; 
                       k1 = i;
                   }
                  
                }  
                System.out.println("年齡最大:"+peoplelist.get(k1));
                break;
            case 3:
                int min = 100;
                int j1,k2 = 0;
                for(int i=1;i<peoplelist.size();i++)
                {
                    j1 = peoplelist.get(i).getage();
                    if(j1<min)
                    {
                        min = j1; 
                        k2 = i;
                    }

                 } 
                System.out.println("年齡最小:"+peoplelist.get(k2));
                break;
            case 4:
                System.out.println("年齡:");
                int input_age = scanner.nextInt();
                ArrayList<People> plist = new ArrayList<People>();
                plist = agenear(input_age);
                for(People people : plist) {
                    System.out.println(people.toString());
                }
                break;
            case 5:
                System.out.println("請輸入省份");
                String find = scanner.next();        
                for (int i = 0; i <peoplelist.size(); i++) 
                {
                    String [] place = peoplelist.get(i).getplace().split("\t");
                    for(String temp : place) {
                        if(find.equals(temp)) {
                            System.out.println("你的同鄉是    "+peoplelist.get(i));
                            break;
                        }
                    }
                    
                } 
                break;
            case 6:
                isTrue = false;
                System.out.println("byebye!");
                break;
            default:
                System.out.println("輸入有誤");
            }
        }
    }

}

 

Comparable介面:

package IDcard;

public class People implements Comparable<People> {

    private    String name = null;
    private    String number = null;
    private    int age = 0;
    private    String sex = null;
    private    String place = null;

    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 int getage() 
    {
        return age;
    }
    public void setage(int age ) 
    {
        this.age = age;
    }
    public String getsex() 
    {
        return sex;
    }
    public void setsex(String sex ) 
    {
        this.sex = sex;
    }
    public String getplace() 
    {
        return place;
    }
    public void setplace(String place) 
    {
        if(this.place == null) {
            this.place = place;
        }else {
            this.place = this.place+ "\t" +place;
        }

    }
    public int compareTo(People o)
    {
        return this.name.compareTo(o.getName());
    }
    public String toString() 
    {
        return  name+"\t"+sex+"\t"+age+"\t"+number+"\t"+place+"\n";
    }
}

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

  (1) 對相關程式碼不熟悉,對有些程式碼的功能不會去運用,主要是由於程式設計練習較少導致。

  (2)對問題分析不夠透徹,很多程式碼放上去之後就會報錯,對錯誤不能及時解決。

  (3)對異常的出現處理之後還是不能使得程式設計問題得到解決,由於對問題的分析不夠所導致。

 

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

程式總體結構說明:包括Suanshu1和main類以及Suanshu類

模組說明:Suanshu1和main類

 

package 練習2;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

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

        Scanner in = new Scanner(System.in);
        Suanshu Suanshu=new Suanshu();
        PrintWriter output = null;
        try {
            output = new PrintWriter("ss.txt");
        } catch (Exception e) {
            //e.printStackTrace();
        }
        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 == Suanshu.chu_fa(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 == Suanshu.chen_fa(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 == Suanshu.jia_fa(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 == Suanshu.jian_fa(a, b)) {
                   sum += 10;
                   System.out.println("恭喜答案正確");
               }
               else {
                   System.out.println("抱歉,答案錯誤");
               }
               break ;

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

 

Suanshu類:

package 練習2;

public class Suanshu
{
       private int a;
       private int b;
        public int  jia_fa(int a,int b)
        {
            return a+b;
        }
        public int   jian_fa(int a,int b)
        {
            if((a-b)<0)
                return 0;
            else
            return a-b;
        }
        public int   chen_fa(int a,int b)
        {
            return a*b;
        }
        public int   chu_fa(int a,int b)
        {
            if(b!=0)
            return a/b;    
            else
        return 0;
        }

        
}

 

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

(1)對問題的分析不夠透徹,沒有深入的去想小學的四則運算是整除的,生成的算術不完全是整除型別的。此外生成的減法運算結果可能為負,這也不符合題目要求。

(2)不知道生成檔名為test.txt的路徑,是通過電腦搜尋得到的。

(3)對程式的設計不夠好,敲程式碼的能力也較差。

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

 

package 改進版;

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

public class Suanshu1 {
    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.jianfa(a, b)) {
                    sum += 10;
                    System.out.println("回答正確!");
                } else {
                    System.out.println("回答錯誤!");
                }
                break;
            }
        }
        System.out.println("最後得分" + sum);
        out.println("最後得分" + sum);
        out.close();
    }
}

 

package 改進版;

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

實驗結果如下圖所示:

 

 

三、實驗總結

    通過本週對泛型程式設計的學習,我瞭解了運用泛型程式設計的程式碼可以被很多不同型別的物件所重用。這使得程式碼的重用性被提高,而且不用很麻煩的再去敲程式碼。這周的實驗有對上週實驗的總結,讓我再次認識到了自己的不足,在今後的學習中仍需要很大的努力。