• 第十周Java实验作业


    实验十  泛型程序设计技术

    实验时间 2018-11-1

    1、实验目的与要求

    (1) 理解泛型概念;

    泛型:也称参数化类型,就是在定义类,接口和方法时,通过类型参数只是将要处理的类型对象。(如ArrayList类)

    (2) 掌握泛型类的定义与使用;

    一个泛型类,就是具有一个或者多个类型变量的类,即创建用类型作为参数的类。一个泛型类定义格式如下:

    class Generics(K,V);

    其中K和V是类中的可变类型的参数。

    (3) 掌握泛型方法的声明与使用;

    泛型方法:除了泛型类之外,还可以只单独定义一个方法作为泛型方法,用于指定泛型参数或者返回值为泛型类型。,留待方法调用时确定。

    泛型方法可以声明在泛型类中,也可以声明在普通类中。

    public class ArrayTool

    {

    public static <E> void insert (E[] ,int i)

    {

    ......

    }

    Public static<E> E valueAt(E[] e,int i)

    {

    ...

    }

    }

    (4) 掌握泛型接口的定义与实现;

    定义:

    public interface IPool<T>

    {

    T get();

    Int add(T t);

    }

    实现:

    public class GenericPool<T> implements IPool<T>

    {

    ...

    }

    public class GenericPool implements IPool<Account>

    {

    ...

    }

    (5)了解泛型程序设计,理解其用途。

    泛类型程序设计:编写代码可以被许多不同类型的对象使用。

    2、实验内容和步骤

    实验1: 导入第8章示例程序,测试程序并进行代码注释。

    测试程序1:

    l 编辑、调试、运行教材311、312页 代码,结合程序运行结果理解程序;

    l 在泛型类定义及使用代码处添加注释;

    l 掌握泛型类的定义及使用。 

    package pair1;
    
    /**
     * @version 1.00 2004-05-10
     * @author Cay Horstmann
     */
    public class Pair<T> //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;
    
    /**
     * @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方法。
          //minmax的返回值是Pair<String>类型的
          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)//定义静态方法minmax
       //实例化以后的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++)//length:String类数组a[]的一个属性
          {
             if (min.compareTo(a[i]) > 0) min = a[i];//compareTo:数组的遍历,通过Ascll码进行比较
             if (max.compareTo(a[i]) < 0) max = a[i];
             //按照字典排序(比较的是字母的ascll编码,大写字母的值比较小
          }
          return new Pair<>(min, max);//返回一个Pair类型的对象。(将这两个数据打包)
       }
    }

    运行结果:

    测试程序2:

    编辑、调试运行教材315 PairTest2,结合程序运行结果理解程序;

    在泛型程序设计代码处添加相关注释;

    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[] 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)//泛型方法
       //使用extends关键字为类型变量设置上界
       {
          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,结合程序运行结果理解程序;

    了解通配符类型的定义及用途。

    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;//必须设置为null,否则会出现空指针异常
       }
       public Pair(T first, T second)//构造器含参数,first和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;
    
    /**
     * @version 1.01 2012-01-26
     * @author Cay Horstmann
     */
    public class PairTest3
    {
       public static void main(String[] args)
       {
           //创建了manger类对象
          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)
       //Pair<? extends Employee>表示任何泛型Pair类型,它的类型参数是Emplooy的子类。?  通配符
       {
          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    swapHelper通配符类型
       }
       // 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);
       }
    }
    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;
       }
    }

    运行结果:

    实验2编程练习:

    编程练习1:实验九编程题总结

    实验九编程练习1总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。

    程序结构:

     Indentity 和 使用了接口的Student类

    package 小陈9;
    
    public  class Student implements Comparable<Student> {
        private    String name;
        private    String number ;
        private    String sex ;
        private    int age;
        private    String province;
     
         
        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 String getsex() {
            return sex ;
        }
        public void setsex(String sex ) {
            this.sex =sex ;
        }
        public int getage() {
            return age;
        }
        public void setage(int age ) {
            this.age=age ;
        }
        public String getprovince() {
            return province;
        }
        public void setprovince(String province) {
            this.province=province ;
        }
    @Override
    public int compareTo(Student other) {
        // TODO Auto-generated method stub
         return this.name.compareTo(other.getName());
    }//compareTo方法比较姓名
    public String toString() {
        return  name+"	"+sex+"	"+age+"	"+number+"	"+province+"
    ";
    }    
    }
    package 小陈9;
    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 Identity{
        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:/身份证号.txt");
            try {
                //利用try 。。 catch  语句进行异常处理
                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();
              //捕获异常
            }
            //读取文件内容
            boolean isTrue = true;
            while (isTrue) {
                System.out.println("选择你的操作,输入正确格式的选项");
                System.out.println("1.字典排序");
                System.out.println("2.输出年龄最大和年龄最小的人");
                System.out.println("3.寻找老乡");
                System.out.println("4.寻找年龄相近的人");
                System.out.println("0.退出");
                int status = scanner.nextInt();
                switch (status) {
                case 1:
                    Collections.sort(studentlist);   //对姓名字典排序           
                    System.out.println(studentlist.toString());
                    break;
                case 2:
                     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 3:
                     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 4:
                    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 0:
                        status = 0;
                        System.out.println("程序已退出!");
                        break;
                   default:
                       System.out.println("输入错误");
                   }
                 }
                }//选择具体操作
            public static int agenear(int age) {      
            int 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;         
          }//找到年龄最大和最小者
          
    }

    程序设计存在的困难与问题:

    (1)编程能力差,对代码的熟悉和了解远远不够,应该多加练习。

    (2)看到问题不会分析,不能很快从中提取出主要的变量和要进行的操作

    实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。

    程序结构:

    yunsuan类 和 jieguo类

    public class yunsuan {
        public static void main(String[] args) {
    
            Scanner in = new Scanner(System.in);
            Pair student=new Pair();
            PrintWriter out = null;
           try {
               out = new PrintWriter("text.txt");
            } catch (FileNotFoundException e) {
                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 c= (int) Math.round(Math.random() * 3);
    
                //生成随机数 ,  用于生成四则运算题目 ,其中c  用于switch语句,生成四则运算的种类

    switch(c) { case 0: System.out.println(i+": "+a+"/"+b+"="); while(b==0) { b = (int) Math.round(Math.random() * 100); } int C = in.nextInt(); out.println(a+"/"+b+"="+C); if (C == student.division(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break; case 1: System.out.println(i+": "+a+"*"+b+"="); int D = in.nextInt(); out.println(a+"*"+b+"="+D); if (D == student.multiply(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break; case 2: System.out.println(i+": "+a+"+"+b+"="); int E = in.nextInt(); out.println(a+"+"+b+"="+E); if (E == student.plus(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break ; case 3: System.out.println(i+": "+a+"-"+b+"="); int F = in.nextInt(); out.println(a+"-"+b+"="+F); if (F == student.minus(a, b)) { sum += 10; System.out.println("right"); } else { System.out.println("false"); } break ; } }//生成四则运算题目,并判断回答是否正确 System.out.println("成绩"+sum); out.println("成绩:"+sum); out.close();
          //输出结果
    } }
    *public class jieguo {
       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;
        }
    
    }

    程序设计存在的困难与问题:

    (1)text文件的输出存在问题

    (2)接口应用存在问题,对于使用接口设计程序不能熟练掌握。

    编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。

    package 小陈1;
    
    public class Pair<T> {
           private T a;
           private T b;
            public Pair()
            {
                a = null;
                b = null;
            }
            public Pair(T a,T b)
            {
                this.a = a;
                this.b = b;
            }
            public T getA()
            {
                return a;
            }
            public T getB()
            {
                return b;
            }
           public int plus(int a,int b)
           {
               return a+b;
           }
           public int minus(int a,int b)
           {
               return a-b;
           }
           public int multiply(int a,int b)
           {
               return a*b;
           }
           public int division(int a,int b)
           {
               if(b!=0 && a%b==0)
                   return a/b;
               else
                   return 0;
           }
               
    }
    package 小陈1;
    
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    
    
    public class yunsuan {
        public static void main(String[] args) {
    
            Scanner in = new Scanner(System.in);
            Pair student=new Pair();
            PrintWriter out = null;
           try {
               out = new PrintWriter("text.txt");
            } catch (FileNotFoundException e) {
                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 c= (int) Math.round(Math.random() * 3);
    
               
               switch(c)
               {
               case 0:
                   System.out.println(i+": "+a+"/"+b+"=");
                   
                   while(b==0)
                   { 
                       b = (int) Math.round(Math.random() * 100);
                }
                   
                int C = in.nextInt();
                out.println(a+"/"+b+"="+C);
                if (C == student.division(a, b)) {
                    sum += 10;
                    System.out.println("right");
                }
                else {
                    System.out.println("false");
                }
                
                break;
                
               case 1:
                   System.out.println(i+": "+a+"*"+b+"=");
                   int D = in.nextInt();
                   out.println(a+"*"+b+"="+D);
                   if (D == student.multiply(a, b)) {
                       sum += 10;
                       System.out.println("right");
                   }
                   else {
                       System.out.println("false");
                   }
                   break;
               case 2:
                   System.out.println(i+": "+a+"+"+b+"=");
                   int E = in.nextInt();
                   out.println(a+"+"+b+"="+E);
                   if (E == student.plus(a, b)) {
                       sum += 10;
                       System.out.println("right");
                   }
                   else {
                       System.out.println("false");
                   }
                   
                   break ;
               case 3:
                   System.out.println(i+": "+a+"-"+b+"=");
                   int F = in.nextInt();
                   out.println(a+"-"+b+"="+F);
                   if (F == student.minus(a, b)) {
                       sum += 10;
                       System.out.println("right");
                   }
                   else {
                       System.out.println("false");
                   }
                   break ;
                  } 
              }//生成四则运算题目,并判断回答是否正确
           System.out.println("成绩"+sum);
            out.println("成绩:"+sum);
             out.close();        
       }
       }

    总结:本周学习了泛类型程序设计,了解到泛型的主要目标是实现Java的类型安全。其主要使用在类,接口,方法中。提高了代码的重用性。存在的问题在于对泛型程序设计的使用不太熟练,还需要继续进行学习。

  • 相关阅读:
    在Ubuntu 20.04 LTS Focal Fossa上安装Deluge
    如何使用命令行快速检查Linux系统的版本
    如何在Debian 10上安装NVM
    如何在CentOS 8上安装Apache ActiveMQ
    如何在Linux中引导时列出启动服务?
    如何检查Linux Mint 20磁盘错误的方法
    如何在Firewalld中打开特定IP地址的端口?
    如何在CentOS 8服务器安装oVirt开源虚拟化管理系统
    如何在Centos 8服务器上安装LogAnalyzer?
    如何在Debian中使用apt从命令行安装程序
  • 原文地址:https://www.cnblogs.com/980303CYR/p/9898541.html
Copyright © 2020-2023  润新知