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

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

 

 

                                                                                                                                                                                                                     實驗十

  泛型程式設計技術

                                                                                                                                                                                                                          實驗時間 201

8-11-4

 

1、實驗目的與要求

(1) 理解泛型概念;

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

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

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

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

2、實驗內容和步驟

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

測試程式1:

編輯、除錯、執行教材311312 程式碼,結合程式執行結果理解程式;

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

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

程式碼:

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; } package pair1;
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);//泛型類物件String Pair類,靜態方法用類名呼叫方法,泛型字串型別,按字典序排序
      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;//length是陣列的屬性值
      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;

/**
 * @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; }
}
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);
      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);
   }
}

結果:

測試程式3:

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

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

程式碼:

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

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;

/**
 * @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 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<>();//也可以用Manager
      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)//採用萬用字元來定義第二個型別變數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); // OK--swapHelper captures wildcard type
   }
   // Can't write public static <T super manager> ...
}

class PairAlg
{
   public static boolean hasNulls(Pair<?> p)//?型別變數的萬用字元,單獨的?表示任何一種型別,T表示一種未知型別
   //將hasNulls轉換成泛型方法
   //測試一個pair是否包含一個null引用
   {
      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);
   }
}

結果:

實驗2:程式設計練習:

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

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

總體結構說明:

主類main,子類card

模組說明:

main

package shen;

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;

public class Main {
    /**
     * 1.檔案讀取模組 利用ArrayList構造studentlist存放檔案內容2. 建立檔案字元流,分類讀取檔案內容 3.try/catch語句捕獲異常
     */
    private static ArrayList<Student> studentlist;

    public static void main(String[] args) {
        studentlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("C:\\Users\\ASUS\\Desktop\\新建資料夾\\身份證號.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 number = linescanner.next();
                String sex = linescanner.next();
                String age = linescanner.next();
                String province = linescanner.nextLine();
                Student student = new Student();
                student.setName(name);
                student.setnumber(number);
                student.setsex(sex);
                int a = Integer.parseInt(age);
                student.setage(a);
                student.setprovince(province);
                studentlist.add(student);

            }
        } catch (FileNotFoundException e) {
            System.out.println("學生資訊檔案找不到");
            e.printStackTrace();
            // 加入的捕獲異常程式碼
        } catch (IOException e) {
            System.out.println("學生資訊檔案讀取錯誤");
            e.printStackTrace();
            // 加入的捕獲異常程式碼
        }
        /*
         * 1.根據實驗要求,選擇具體操作的模組 2.利用switch語句選擇具體的操作
         */
        boolean isTrue = true;
        while (isTrue) {
            System.out.println("選擇你的操作,輸入正確格式的選項");
            System.out.println("A.字典排序");
            System.out.println("B.輸出年齡最大和年齡最小的人");
            System.out.println("C.尋找老鄉");
            System.out.println("D.尋找年齡相近的人");
            System.out.println("F.退出");
            String m = scanner.next();
            switch (m) {
            case "A":
                Collections.sort(studentlist);
                System.out.println(studentlist.toString());
                break;
            case "B":
                int max = 0, min = 100;
                int j, k1 = 0, k2 = 0;
                for (int i = 1; i < studentlist.size(); i++) {
                    j = studentlist.get(i).getage();
                    if (j > max) {
                        max = j;
                        k1 = i;
                    }
                    if (j < min) {
                        min = j;
                        k2 = i;
                    }

                }
                System.out.println("年齡最大:" + studentlist.get(k1));
                System.out.println("年齡最小:" + studentlist.get(k2));
                break;
            case "C":
                System.out.println("老家?");
                String find = scanner.next();
                String place = find.substring(0, 3);
                for (int i = 0; i < studentlist.size(); i++) {
                    if (studentlist.get(i).getprovince().substring(1, 4).equals(place))
                        System.out.println("老鄉" + studentlist.get(i));
                }
                break;

            case "D":
                System.out.println("年齡:");
                int yourage = scanner.nextInt();
                int near = agenear(yourage);
                int value = yourage - studentlist.get(near).getage();
                System.out.println("" + studentlist.get(near));
                break;
            case "F":
                isTrue = false;
                System.out.println("退出程式!");
                break;
            default:
                System.out.println("輸入有誤");

            }
        }
    }

    /*
     * 對年齡資料進行相應的處理
     */
    public static int agenear(int age) {
        int j = 0, min = 53, value = 0, k = 0;
        for (int i = 0; i < studentlist.size(); i++) {
            value = studentlist.get(i).getage() - age;
            if (value < 0)
                value = -value;
            if (value < min) {
                min = value;
                k = i;
            }
        }
        return k;
    }

}

Main

card:

package shen;

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;

public class Main {
    /**
     * 1.檔案讀取模組 利用ArrayList構造studentlist存放檔案內容2. 建立檔案字元流,分類讀取檔案內容 3.try/catch語句捕獲異常
     */
    private static ArrayList<Student> studentlist;

    public static void main(String[] args) {
        studentlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("C:\\Users\\ASUS\\Desktop\\新建資料夾\\身份證號.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 number = linescanner.next();
                String sex = linescanner.next();
                String age = linescanner.next();
                String province = linescanner.nextLine();
                Student student = new Student();
                student.setName(name);
                student.setnumber(number);
                student.setsex(sex);
                int a = Integer.parseInt(age);
                student.setage(a);
                student.setprovince(province);
                studentlist.add(student);

            }
        } catch (FileNotFoundException e) {
            System.out.println("學生資訊檔案找不到");
            e.printStackTrace();
            // 加入的捕獲異常程式碼
        } catch (IOException e) {
            System.out.println("學生資訊檔案讀取錯誤");
            e.printStackTrace();
            // 加入的捕獲異常程式碼
        }
        /*
         * 1.根據實驗要求,選擇具體操作的模組 2.利用switch語句選擇具體的操作
         */
        boolean isTrue = true;
        while (isTrue) {
            System.out.println("選擇你的操作,輸入正確格式的選項");
            System.out.println("A.字典排序");
            System.out.println("B.輸出年齡最大和年齡最小的人");
            System.out.println("C.尋找老鄉");
            System.out.println("D.尋找年齡相近的人");
            System.out.println("F.退出");
            String m = scanner.next();
            switch (m) {
            case "A":
                Collections.sort(studentlist);
                System.out.println(studentlist.toString());
                break;
            case "B":
                int max = 0, min = 100;
                int j, k1 = 0, k2 = 0;
                for (int i = 1; i < studentlist.size(); i++) {
                    j = studentlist.get(i).getage();
                    if (j > max) {
                        max = j;
                        k1 = i;
                    }
                    if (j < min) {
                        min = j;
                        k2 = i;
                    }

                }
                System.out.println("年齡最大:" + studentlist.get(k1));
                System.out.println("年齡最小:" + studentlist.get(k2));
                break;
            case "C":
                System.out.println("老家?");
                String find = scanner.next();
                String place = find.substring(0, 3);
                for (int i = 0; i < studentlist.size(); i++) {
                    if (studentlist.get(i).getprovince().substring(1, 4).equals(place))
                        System.out.println("老鄉" + studentlist.get(i));
                }
                break;

            case "D":
                System.out.println("年齡:");
                int yourage = scanner.nextInt();
                int near = agenear(yourage);
                int value = yourage - studentlist.get(near).getage();
                System.out.println("" + studentlist.get(near));
                break;
            case "F":
                isTrue = false;
                System.out.println("退出程式!");
                break;
            default:
                System.out.println("輸入有誤");

            }
        }
    }

    /*
     * 對年齡資料進行相應的處理
     */
    public static int agenear(int age) {
        int j = 0, min = 53, value = 0, k = 0;
        for (int i = 0; i < studentlist.size(); i++) {
            value = studentlist.get(i).getage() - age;
            if (value < 0)
                value = -value;
            if (value < min) {
                min = value;
                k = i;
            }
        }
        return k;
    }

}

Main

問題:目前程式設計存在的困難與問題:讀檔案時,檔案路徑不正確,無法找到檔案。

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

總體結構說明:

主類test和子類yunsuan

模組說明:

package demo;

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

public class Test {
    public static void main(String[] args) {
        //檔案輸出模組,呼叫建構函式

        @SuppressWarnings("resource")
        Scanner in = new Scanner(System.in);
        Demo demo=new Demo();
        //建立檔案字元流,將output中的內容設為空(null)
        PrintWriter output = null;
        try {
            output = new PrintWriter("test.txt");//將out結果輸出到test.txt中
        } catch (Exception e) {
            e.printStackTrace();
        }
        int sum = 0; //定義一個sum,計算成績
        
        //四則運算生成模組,生成10道題目
        for (int i = 0; i < 10; i++) {

            int a = (int) Math.round(Math.random() * 100);
            int b = (int) Math.round(Math.random() * 100);
            int c = (int) Math.round(Math.random() * 3);
            switch (c) {
            case 0:
                System.out.println(a + "+" + b + "=");
                int d0 = in.nextInt();
                output.println(a + "+" + b + "=" + d0);
                if (d0 == demo.demo1(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正確");
                } else {
                    System.out.println("抱歉,答案錯誤");
                }
                break;
            case 1:
                while (a < b) {
                    int x = a;
                    a = b;
                    b = x;
                }
                System.out.println(a + "-" + b + "=");
                int d1 = in.nextInt();
                output.println(a + "-" + b + "=" + d1);
                if (d1 == demo.demo2(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正確");
                } else {
                    System.out.println("抱歉,答案錯誤");
                }
                break;
            case 2:
                System.out.println(a + "*" + b + "=");
                int d2 = in.nextInt();
                output.println(a + "*" + b + "=" + d2);
                if (d2 == demo.demo3(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正確");
                } else {
                    System.out.println("抱歉,答案錯誤");
                }
                break;
            case 3:
                while (b == 0 || a % b != 0) {
                    a = (int) Math.round(Math.random() * 100);
                    b = (int) Math.round(Math.random() * 100);
                }
                System.out.println(a + "/" + b + "=");
                int d3 = in.nextInt();
                output.println(a + "/" + b + "=" + d3);
                if (d3 == demo.demo4(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正確");
                } else {
                    System.out.println("抱歉,答案錯誤");
                }
                break;

            }

        }

        System.out.println("你的得分為" + sum);
        output.println("你的得分為" + sum); //將迴圈結果輸出到test.txt中
        output.close();
    }
}

Test
package demo;

public class yunsuan {
       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;            
        }

}

yunsuan

問題:對printwrite不太瞭解。

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

程式碼:

package demo;

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

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

        @SuppressWarnings("resource")
        Scanner in = new Scanner(System.in);
        Demo demo=new Demo();

        PrintWriter output = null;
        try {
            output = new PrintWriter("test.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
        int sum = 0;

        for (int i = 0; i < 10; i++) {

            int a = (int) Math.round(Math.random() * 100);
            int b = (int) Math.round(Math.random() * 100);
            int c = (int) Math.round(Math.random() * 3);
            switch (c) {
            case 0:
                System.out.println(a + "+" + b + "=");
                int d0 = in.nextInt();
                output.println(a + "+" + b + "=" + d0);
                if (d0 == demo.demo1(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正確");
                } else {
                    System.out.println("抱歉,答案錯誤");
                }
                break;
            case 1:
                while (a < b) {
                    int x = a;
                    a = b;
                    b = x;
                }
                System.out.println(a + "-" + b + "=");
                int d1 = in.nextInt();
                output.println(a + "-" + b + "=" + d1);
                if (d1 == demo.demo2(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正確");
                } else {
                    System.out.println("抱歉,答案錯誤");
                }
                break;
            case 2:
                System.out.println(a + "*" + b + "=");
                int d2 = in.nextInt();
                output.println(a + "*" + b + "=" + d2);
                if (d2 == demo.demo3(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正確");
                } else {
                    System.out.println("抱歉,答案錯誤");
                }
                break;
            case 3:
                while (b == 0 || a % b != 0) {
                    a = (int) Math.round(Math.random() * 100);
                    b = (int) Math.round(Math.random() * 100);
                }
                System.out.println(a + "/" + b + "=");
                int d3 = in.nextInt();
                output.println(a + "/" + b + "=" + d3);
                if (d3 == demo.demo4(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正確");
                } else {
                    System.out.println("抱歉,答案錯誤");
                }
                break;

            }

        }

        System.out.println("你的得分為" + sum);
        output.println("你的得分為" + sum);
        output.close();
    }
}

Test
package demo;

public class yunsuan {
       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;            
        }

}

yunsuan

結果:

實驗總結:通過這周的學習,我瞭解了泛型設計技術的概念,以及它的好處和限制,基本上會運用泛型技術設計程式,但是在很多知識的運用方面仍然不太懂,在之後的學習中要更加努力,課後要多練習,也希望老師能更加詳細的講解。