張季躍 201771010139《面向對象程序設計(java)》第十週學習總結

張季躍 201771010139《面向對象程序設計(java)》第周學習總結java

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

一.l何謂泛型程序設計:數組

  1. JDK5.0中增長的泛型類型,是Java語言中類型 安全的一次重要改進。
  2. 泛型:也稱參數化類型(parameterizedtype), 就是在定義類、接口和方法時,經過類型參數指 示將要處理的對象類型。
  3. 泛型程序設計(Genericprogramming):編寫 代碼能夠被不少不一樣類型的對象所重用。

二.泛型接口的定義安全

  1.定義dom

public interface IPool <T>學習

 {測試

      T get();this

int add(T t);spa

 }設計

2.實現:

public class GenericPool<T> implements IPool<T>

{

 }

 

}

public class GenericPoolimplements IPool<Account>

{

}

二.泛型變量的限定:

l1.定義泛型變量的上界: public class NumberGeneric< T extends Number>

  1. 泛型變量上界的說明

(1)上述聲明規定了NumberGeneric類所能處理的 泛型變量類型需和Number有繼承關係; u

(2)extends關鍵字所聲明的上界既能夠是一個類, 也能夠是一個接口;

l3.<TextendsBoundingType>表示T應該是綁定 類型的子類型。

l4.一個類型變量或通配符能夠有多個限定,限定類 型用「&」分割。

 

三.泛型類的約束與侷限性

  1. 不能用基本類型實例化類型參數 l
  2. 運行時類型查詢只適用於原始類型 l
  3. 不能拋出也不能捕獲泛型類實例 l
  4. 參數化類型的數組不合法 l
  5. 不能實例化類型變量 l
  6. 泛型類的靜態上下文中類型變量無效 l
  7. 注意擦除後的衝突

四.泛型類型的繼承規則

  1. Java中的數組是協變的(covariant)。
  2. Java中泛型類不具協變性。若是可以將 List<Integer>賦給List<Number>。那麼下面的代碼 就容許將非Integer的內容放入List<Integer>:

List<Integer> li = new ArrayList<Integer>();

 List<Number> ln = li; // illegal

ln.add(new Float(3.1415));

  1. 泛型類可擴展或實現其它的泛型類。

五.通配符類型及使用方法

 

  1. 通配符:

  1)「?」符號代表參數的類型能夠是任何一種類 型,它和參數T的含義是有區別的。T表示一種 未知類型,而「?」表示任何一種類型。這種 通配符通常有如下三種用法:

  –單獨的,用於表示任何類型。 –?extends type,表示帶有上界。 –super type,表示帶有下界。

 

 

第二部分:實驗部分

一、實驗目的與要求

(1) 理解泛型概念;

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

(3) 掌握泛型方法的聲明與使用;

(4) 掌握泛型接口的定義與實現;

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

二、實驗內容和步驟

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

測試程序1:

編輯、調試、運行教材3十一、312頁 代碼,結合程序運行結果理解程序;

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

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

Pair<T>

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

}

 

 

PairTest1

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

         if (max.compareTo(a[i]) < 0) max = a[i];

      }

      return new Pair<>(min, max);

   }

}

測試結果:

 

 

測試程序2:

編輯、調試運行教材315頁 PairTest2,結合程序運行結果理解程序;

在泛型程序設計代碼處添加相關注釋;

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

測試程序:

Pair<T>

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

}

PairTest2

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:

用調試運行教材335頁 PairTest3,結合程序運行結果理解程序;

瞭解通配符類型的定義及用途。

實驗程序;

Employee

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;

   }

}

 

Manager

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;

   }

}

Pair<T>

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

}

PairTest3

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<>();

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

 

   public static <T> void swapHelper(Pair<T> p)

   {

      T t = p.getFirst();

      p.setFirst(p.getSecond());

      p.setSecond(t);

   }

}

 

測試結果:

 

 

 

實驗2:編程練習:

編程練習1:實驗九編程題總結

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

   整體結構說明:主類:Main      子類:People

   模塊說明:主類Main:讀取文件txt,將文件導入程序,並對文件選擇進行五種不一樣的操做

             子類People:聲明屬性,對數據進行處理

Main

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 實驗 {

 

    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("C:\\Users\\張季躍\\Desktop\\身份證號.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("再見!");

                break;

            default:

                System.out.println("輸入有誤");

            }

        }

    }

 

}

People:

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

    }

}

 

   目前的困難與問題:

   編寫程序時仍是有許多不懂的東西,並且就算寫完仍是有相似於找不到文件和屬性不對之類的問題,即便在請教同窗將問題解決以後仍是不太熟練。

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

   整體結構說明:主類:實驗3

   模塊說明:隨機選取數據,生成十個題目進行四則運算,並與輸入的結果進行比較判斷對錯,並計算得分

主類實驗3:

package 實驗3-2;

import java.util.Random;

import java.util.Scanner;

public class 實驗3{

int sum;

public static void main(String[] args) {

實驗3 t=new 實驗3();

System.out.println("考試開始");

t.sum=0;

Random r=new Random();

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

t.core();

}

System.out.println("考試結束");

System.out.println("你的總分爲"+t.sum);

}

private void core() {

Random r=new Random();

int m,n;

m=r.nextInt(11);

n=m%4;

switch(n) {

case 0:

int a ,b,c;

a=r.nextInt(101);

b=r.nextInt(101);

System.out.println(a+"+"+"("+b+")"+"=");

Scanner x=new Scanner(System.in);

c=x.nextInt();

if(c!=a+b)

System.out.println("計算失誤");

else {

System.out.println("計算正確");

sum=sum+10;

}

break;

case 1:

int h,g,f;

h=r.nextInt(101);

g=r.nextInt(101);

System.out.println(h+"-"+"("+g+")"+"= ");

Scanner u=new Scanner(System.in);

f=u.nextInt();

if(f!=h-g)

System.out.println("計算失誤");

else {

System.out.println("計算正確");

sum=sum+10;

}

break;

case 2:

int q,w,e;

q=r.nextInt(101);

w=r.nextInt(101);

System.out.println(q+"*"+"("+w+")"+"= ");

  Scanner y=new Scanner(System.in);

e=y.nextInt();

if(e!=q*w)

System.out.println("計算失誤");

else {

System.out.println("計算正確");

sum=sum+10;

}

break;

case 3:

double j,k,l;

j=r.nextInt(101);

k=r.nextInt(101);

if(k==0)

k++;

System.out.println(j+"/"+"("+k+")"+"= ");

Scanner z=new Scanner(System.in);

l=z.nextDouble();

if(l!=(j/k)/1.00)

System.out.println("計算失誤");

else {

System.out.println("計算正確");

sum=sum+10;

}

break;

}

}

}  

 

   目前的困難與問題:沒有將最終結果輸入到txt文檔中,並且再進行除法運算時隨機生成的數據最低位爲小數點後一位

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

實驗程序:

package test;

import java.util.Random;

import java.io.FileOutputStream;

import java.io.PrintStream;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class 實驗3{

int sum;

public static void main(String[] args) throws FileNotFoundException {

實驗3 t=new 實驗3();
PrintStream out = System.out;
PrintStream ps = new PrintStream("C:\\Users\\張季躍\\Desktop\\第十週實驗報告\\text.txt");
System.setOut(ps);
System.out.println("kaishiks");

System.out.println("本次測試共十道題,每題十分,滿分一百分");

t.sum=0;

Random r=new Random();

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

t.core();

}

System.out.println("考試結束");

System.out.println("你的總分爲"+t.sum);

}

private void core() throws FileNotFoundException {

Random r=new Random();

int m,n;

m=r.nextInt(11);

n=m%4;

switch(n) {

case 0:

int a ,b,c;

a=r.nextInt(101);

b=r.nextInt(101);

System.out.println(a+"+"+"("+b+")"+"=");

Scanner x=new Scanner(System.in);

c=x.nextInt();

if(c!=a+b)

System.out.println("回答錯誤");

else {

System.out.println("回答正確");

sum=sum+10;

}

break;

case 1:

int h,g,f;

h=r.nextInt(101);

g=r.nextInt(101);

System.out.println(h+"-"+"("+g+")"+"= ");

Scanner u=new Scanner(System.in);

f=u.nextInt();

if(f!=h-g)

System.out.println("回答錯誤");

else {

System.out.println("回答正確");

sum=sum+10;

}

break;

case 2:

int q,w,e;

q=r.nextInt(101);

w=r.nextInt(101);

System.out.println(q+"*"+"("+w+")"+"= ");

Scanner y=new Scanner(System.in);

e=y.nextInt();

if(e!=q*w)

System.out.println("回答錯誤");

else {

System.out.println("回答正確");

sum=sum+10;

}

break;

case 3:

double j,k,l;

j=r.nextInt(101);

k=r.nextInt(101);

if(k==0)

k++;

System.out.println(j+"/"+"("+k+")"+"= ");

Scanner z=new Scanner(System.in);

l=z.nextDouble();

if(l!=(j/k)/1.00)

System.out.println("回答錯誤");

else {

System.out.println("回答正常");

sum=sum+10;

}

PrintStream out = System.out;
break;

}

}

}

實驗結果:

 

 

 

第三部分:實驗總結:

     這一週我主要學習了泛型程序設計,泛型接口的定義,泛型變量的限定和通配符類型及使用方法,但在本週的實驗過程當中我發現我對泛型的掌握仍是不熟練,即便是修改上一次的程序也力不從心。其次,在對上一次實驗報告的總結中我也發現了本身在上一次程序中的許多錯誤,並嘗試對其進行改正。

相關文章
相關標籤/搜索