杨玲 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. 实验总结:

         通过本次实验我理解了泛型的概念;掌握了泛型类的定义与使用; 掌握了泛型方法的声明与使用; 掌握了泛型接口的定义与实现;了解了泛型程序设计和它的用途。

猜你喜欢

转载自www.cnblogs.com/yanglinga/p/9890510.html