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. HopperLocalDate.of(1815, 12, 10), // A. LovelaceLocalDate.of(1903, 12, 3), // J. von NeumannLocalDate.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<>();//也可以用ManagerminmaxBonus(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

结果:

实验总结:本周学习了有关泛型的知识,泛型接口的定义与实现,学会运用泛型技术设计程序,了解泛型程序设计,理解其用途。但本周所学知识中通配符的运用理解还有待加强。

转载于:https://www.cnblogs.com/zd0421/p/9904020.html

201771010137 赵栋《面向对象程序设计(java)》第十周学习总结相关推荐

  1. 201871010115——马北《面向对象程序设计JAVA》第二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  2. 20145302张薇《Java程序设计》第十周学习总结

    20145302 <Java程序设计>第十周学习总结 客户端和服务器端功能 客户端程序功能列表: 接收用户控制台输入 判断输入内容是否合法 按照协议格式发送数据 根据服务器端的反馈给出相应 ...

  3. 201521123038 《Java程序设计》 第十周学习总结

    201521123038 <Java程序设计> 第十周学习总结 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结异常与多线程相关内容. 2. 书面作业 本次PTA作业题 ...

  4. 20155230 2016-2017-2 《Java程序设计》第十周学习总结

    20155230 2016-2017-2 <Java程序设计>第十周学习总结 教材学习内容总结 网络编程:就是在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就是把数据发 ...

  5. # 20155337 2016-2017-2 《Java程序设计》第十周学习总结

    20155337 2016-2017-2 <Java程序设计>第十周学习总结 教材学习内容总结 网络编程 •网络编程就是在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就 ...

  6. 20175227张雪莹 2018-2019-2 《Java程序设计》第十周学习总结

    20175227张雪莹 2018-2019-2 <Java程序设计>第十周学习总结 教材学习内容总结 第十二章 Java多线程机制 进程与线程 线程是比进程更小的执行单位,一个进程在其执行 ...

  7. 20155305乔磊2016-2017-2《Java程序设计》第十周学习总结

    20155305乔磊2016-2017-2<Java程序设计>第十周学习总结 教材学习内容总结 Java的网络编程 网络编程 网络编程就是在两个或两个以上的设备(例如计算机)之间传输数据. ...

  8. 《数据结构与面向对象程序设计》第1周学习总结

    20182316胡泊 2019-2020-1 <数据结构与面向对象程序设计>第1周学习总结 教材学习内容总结 简单java程序是有哪些部分组成的 Java程序好的排版布局是怎样的 程序开发 ...

  9. 20175212童皓桢 《Java程序设计》第十周学习总结

    学号 2016-2017-2 <Java程序设计>第X周学习总结 教材学习内容总结 一.Java中的线程的状态 建的线程在它的一个完整的生命周期中通常要经历如下的四种状态: 1.新建: 当 ...

  10. 四十八.面向对象程序设计——Java语言第一周编程题:分数

    题目内容: 设计一个表示分数的类Fraction.这个类用两个int类型的变量分别表示分子和分母. 这个类的构造函数是: Fraction(int a, int b) 构造一个a/b的分数. 这个类要 ...

最新文章

  1. mysql 事务补偿_TCC补偿性策略_彻底学习数据库事务 seata分布式事务 共享 排它锁 死锁 索引 Spring事务 隔离级别等_MySQL视频-51CTO学院...
  2. ES6与canvas实现鼠标小球跟随效果
  3. windows7下安装MongoDB数据库
  4. 用户NT AUTHORITYNETWORK SERVICE登录失败解决方法
  5. Acwing 276. I-区域
  6. 手机工商银行怎么转账_工商银行信用卡要哪些申请条件?想成功办理你需要了解这些!...
  7. 如果 AI 和算法无罪,那么谁在杀死穷人?
  8. 《虚拟化技术原理与实现》读书笔记之前序
  9. vant 项目_基于 vue3.x+vant3.x 搭建示例项目
  10. nginx 优化,突破十万并发
  11. 互联网分布式微服务云平台规划分析--SSO单点登录系统
  12. Better And Better for Mac(Mac手势神器BAB)中文版
  13. python env虚拟环境
  14. python多任务之——线程简述
  15. Python进阶练习题,新手快码起来
  16. delphi连接mysql不用添加dsn_Delphi]delphi中动态创建MySQL的ODBC连接 .
  17. oracle优化技巧
  18. 卡方检验有哪些指标?卡方值怎么计算?
  19. 为了写好代码,你坚持了哪些好习惯?
  20. C++ 注释风格建议

热门文章

  1. Mysql 中的各种“删除”。删除数据库、删除表、删除字段
  2. git使用meld的方法
  3. CC2530基础实验:(1)按键控制LED跑马灯
  4. 【数据挖掘】数据统计性描述与相似度
  5. 【C++】解引用 (及指针) 和 引用 的概念区别
  6. JS案例学习——随机点名案例
  7. Vlan和pvlan全面解析
  8. 多余的读写端口什么时候会对程序造成影响_RFID叉车仓储|RFID叉车读写器在智能仓库收发货环节中的应用...
  9. 学生信息管理系统之用户登录:用户登录流程
  10. 不看公式自己复原魔方