项目

内容

这个作业属于哪个课程

https://www.cnblogs.com/nwnu-daizh/

这个作业的要求在哪里

https://www.cnblogs.com/nwnu-daizh/p/11703678.html

作业学习目标

  1. 掌握接口定义方法;
  2. 掌握实现接口类的定义要求;
  3. 掌握实现了接口类的使用要求;
  4. 理解程序回调设计模式;
  5. 掌握Comparator接口用法;
  6. 掌握对象浅层拷贝与深层拷贝方法;
  7. 掌握Lambda表达式语法;
  8. 了解内部类的用途及语法要求。

第一部分:总结第六章理论知识

第二部分:实验部分

实验内容和步骤

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

测试程序1:

  编辑、编译、调试运行阅读教材214页-215页程序6-1、6-2,理解程序并分析程序运行结果;

  在程序中相关代码处添加新知识的注释。

  掌握接口的实现用法;

  掌握内置接口Compareable的用法。

6-1源代码:

package interfaces;

//使用 implements 关键字实现泛型  Comparable<Employee>接口
public class Employee implements Comparable<Employee>
{
private String name;
private double salary; public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
} public String getName()
{
return name;
} public double getSalary()
{
return salary;
} public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
} /**
* Compares employees by salary
* @param other another Employee object
* @return a negative value if this employee has a lower salary than
* otherObject, 0 if the salaries are the same, a positive value otherwise
*/
public int compareTo(Employee other) //compareTo方法
{
return Double.compare(salary, other.salary); //通过salary进行排序
}//(使用静态Double.compare方法,如果第一个参数小于第二个参数,它会返回一个负值;如果二者相等则返回0;否则返回一个正值。)
}

6-2源代码:

package interfaces;

import java.util.*;

/**
* This program demonstrates the use of the Comparable interface.
* @version 1.30 2004-02-27
* @author Cay Horstmann
*/
public class EmployeeSortTest
{
public static void main(String[] args)
{
var staff = new Employee[3]; staff[0] = new Employee("Harry Hacker", 35000);
staff[1] = new Employee("Carl Cracker", 75000);
staff[2] = new Employee("Tony Tester", 38000); Arrays.sort(staff); //使用Arrays类中sort方法对对象数组进行排序 // print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}

运行结果:

修改为通过姓名进行排序输出:

测试程序2:

  编辑、编译、调试以下程序,结合程序运行结果理解程序;

代码:

package InterfaceTest;

interface A
{
double g=9.8;
void show();
}
class C implements A
{
public void show()
{
System.out.println("g="+g);
}
}
class InterfaceTest
{ public static void main(String[] args) {
A a = new C();
a.show();
System.out.println("g="+C.g);
} }

运行结果:

测试程序3:

  在elipse IDE中调试运行教材223页6-3,结合程序运行结果理解程序;

  26行、36行代码参阅224页,详细内容涉及教材12章。

  在程序中相关代码处添加新知识的注释。

   掌握回调程序设计模式;

源代码:

package timer;

/**
@version 1.02 2017-12-14
@author Cay Horstmann
*/ import java.awt.*;
import java.awt.event.*;
import java.time.*;
import javax.swing.*; public class TimerTest
{
public static void main(String[] args)
{
var listener = new TimePrinter(); //创建类对象 // construct a timer that calls the listener (构造一个调用侦听器的计时器)
// once every second
Timer t = new Timer(1000, listener); //Timer构造器,第一个参数是发出通告的时间间隔(10秒),第二个参数是监听器对象
t.start(); //启动定时器 // keep program running until the user selects "OK" (保持程序运行直到用户选择“OK”)
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
//定义一个实现ActionListener接口的类
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event) //调用actionPerformed方法,ActionEvent参数提供了事件的相关信息
{
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
Toolkit.getDefaultToolkit().beep(); //获得默认的工具箱;发出一声铃响
}
}

运行结果:

测试程序4:

  调试运行教材229页-231页程序6-4、6-5,结合程序运行结果理解程序;

  在程序中相关代码处添加新知识的注释。

  掌握对象克隆实现技术;

  掌握浅拷贝和深拷贝的差别。

6-4 CloneTest.java 源代码:

package clone;

/**
* This program demonstrates cloning.
* @version 1.11 2018-03-16
* @author Cay Horstmann
*/
public class CloneTest
{
public static void main(String[] args) throws CloneNotSupportedException
{
Employee original = new Employee("John Q. Public", 50000);
original.setHireDay(2000, 1, 1);
Employee copy = original.clone(); //使用clone方法,copy是一个新对象,它的初始状态与original相同,但它们各有各自不同的状态
copy.raiseSalary(10);
copy.setHireDay(2002, 12, 31);
System.out.println("original=" + original);
System.out.println("copy=" + copy);
}
}

6-5源代码:

package clone;

import java.util.Date;
import java.util.GregorianCalendar; //使用implements关键字实现Cloneable接口
public class Employee implements Cloneable
{
private String name;
private double salary;
private Date hireDay; public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
hireDay = new Date();
} //Employee和Date类实现cloneable接口
//Object类的clone方法抛出一个CloneNotSupportedException 异常
//声明这个异常
public Employee clone() throws CloneNotSupportedException
{
// call Object.clone() (调用Object.clone())
Employee cloned = (Employee) super.clone(); //super.clone()克隆可变字段 // clone mutable fields
cloned.hireDay = (Date) hireDay.clone(); //克隆可变字段 return cloned;
} /**
* Set the hire day to a given date.
* @param year the year of the hire day
* @param month the month of the hire day
* @param day the day of the hire day
*/
public void setHireDay(int year, int month, int day)
{
Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime(); // example of instance field mutation (实例字段变异示例)
hireDay.setTime(newHireDay.getTime());
} public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
} public String toString()
{
return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
}
}

运行结果:

实验2 导入第6章示例程序6-6,学习Lambda表达式用法。

  调试运行教材233页-234页程序6-6,结合程序运行结果理解程序;

  在程序中相关代码处添加新知识的注释。

  将27-29行代码与教材223页程序对比,将27-29行代码与此程序对比,体会Lambda表达式的优点。

6-6源代码:

package lambda;

import java.util.*;

import javax.swing.*;
import javax.swing.Timer; /**
* This program demonstrates the use of lambda expressions.
* @version 1.0 2015-05-12
* @author Cay Horstmann
*/
public class LambdaTest
{
public static void main(String[] args)
{
var planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune" }; //数组
System.out.println(Arrays.toString(planets));
System.out.println("Sorted in dictionary order:");
Arrays.sort(planets); //Arrays.sort方法,对数组排序
System.out.println(Arrays.toString(planets));
System.out.println("Sorted by length:");
Arrays.sort(planets, (first, second) -> first.length() - second.length()); //lambda表达式
System.out.println(Arrays.toString(planets)); var timer = new Timer(1000, event -> //Timer构造器
System.out.println("The time is " + new Date()));
timer.start(); // keep program running until user selects "OK" (保持程序运行直到用户选择“OK”)
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}

运行结果:

实验3: 编程练习

  编制一个程序,将身份证号.txt 中的信息读入到内存中;

  按姓名字典序输出人员信息;

  查询最大年龄的人员信息;

  查询最小年龄人员信息;

  输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;

  查询人员中是否有你的同乡。

代码:

package ID;
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.Scanner;
import java.util.Collections;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*; public class Test extends JFrame {
private static ArrayList<Citizen> citizenlist;
private static ArrayList<Citizen> list;
private JPanel panel;
private JPanel buttonPanel;
private static final int DEFAULT_WITH = 600;
private static final int DEFAULT_HEIGHT = 300; public Test(){
citizenlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("F://身份证号.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 id = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String birthplace = linescanner.nextLine();
Citizen citizen = new Citizen();
citizen.setName(name);
citizen.setId(id);
citizen.setSex(sex);
int ag = Integer.parseInt(age);
citizen.setage(ag);
citizen.setBirthplace(birthplace);
citizenlist.add(citizen); }
} catch (FileNotFoundException e) {
System.out.println("信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("信息文件读取错误");
e.printStackTrace();
}
panel = new JPanel();
panel.setLayout(new BorderLayout());
JTextArea jt = new JTextArea();
panel.add(jt);
add(panel, BorderLayout.NORTH);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 7));
JButton jButton = new JButton("按姓名字典序输出人员信息");
JButton jButton1 = new JButton("查询年龄最大和年龄最小的人员");
JLabel lab = new JLabel("查询是否有你的老乡");
JTextField jt1 = new JTextField();
JLabel lab1 = new JLabel("查找年龄与你相近的人:");
JTextField jt2 = new JTextField();
JLabel lab2 = new JLabel("输入你的身份证号码:");
JTextField jt3 = new JTextField();
JButton jButton2 = new JButton("退出");
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Collections.sort(citizenlist);
jt.setText(citizenlist.toString());
}
});
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int max = 0, min = 100;
int j, k1 = 0, k2 = 0;
for (int i = 1; i < citizenlist.size(); i++) {
j = citizenlist.get(i).getage();
if (j > max) {
max = j;
k1 = i;
}
if (j < min) {
min = j;
k2 = i;
} }
jt.setText("年龄最大:" + citizenlist.get(k1) + "年龄最小:" + citizenlist.get(k2));
}
});
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
System.exit(0);
}
});
jt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String find = jt1.getText();
String text="";
String place = find.substring(0, 3);
for (int i = 0; i < citizenlist.size(); i++) {
if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place)) {
text+="\n"+citizenlist.get(i);
jt.setText("老乡:" + text);
}
}
}
});
jt2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String yourage = jt2.getText();
int a = Integer.parseInt(yourage);
int near = agenear(a);
int value = a - citizenlist.get(near).getage();
jt.setText("年龄相近:" + citizenlist.get(near));
}
});
jt3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
list = new ArrayList<>();
Collections.sort(citizenlist);
String key = jt3.getText();
for (int i = 1; i < citizenlist.size(); i++) {
if (citizenlist.get(i).getId().contains(key)) {
list.add(citizenlist.get(i));
jt.setText("emmm!你可能是:\n" + list);
}
}
}
});
buttonPanel.add(jButton);
buttonPanel.add(jButton1);
buttonPanel.add(lab);
buttonPanel.add(jt1);
buttonPanel.add(lab1);
buttonPanel.add(jt2);
buttonPanel.add(lab2);
buttonPanel.add(jt3);
buttonPanel.add(jButton2);
add(buttonPanel, BorderLayout.SOUTH);
setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
} public static int agenear(int age) {
int min = 53, value = 0, k = 0;
for (int i = 0; i < citizenlist.size(); i++) {
value = citizenlist.get(i).getage() - age;
if (value < 0)
value = -value;
if (value < min) {
min = value;
k = i;
}
}
return k;
} }
package ID;
public class Citizen implements Comparable<Citizen> { private String name;
private String id;
private String sex;
private int age;
private String birthplace;
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} 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 getBirthplace() {
return birthplace;
} public void setBirthplace(String birthplace) {
this.birthplace = birthplace;
} public int compareTo(Citizen other) {
return this.name.compareTo(other.getName());
} public String toString() {
return name + "\t" + sex + "\t" + age + "\t" + id + "\t" + birthplace + "\n";
}
}
package ID;
import java.awt.*;
import javax.swing.*; public class ButtonTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new Test();
frame.setTitle("身份证");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

结果:

实验4:内部类语法验证实验

实验程序1:

  编辑、调试运行教材246页-247页程序6-7,结合程序运行结果理解程序;

  了解内部类的基本用法。

6-7源代码:

package innerClass;

import java.awt.*;
import java.awt.event.*;
import java.time.*; import javax.swing.*; /**
* This program demonstrates the use of inner classes.
* @version 1.11 2017-12-14
* @author Cay Horstmann
*/
public class InnerClassTest
{
public static void main(String[] args)
{
var clock = new TalkingClock(1000, true);
clock.start(); // keep program running until the user selects "OK"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
} /**
* A clock that prints the time in regular intervals.
*/
class TalkingClock
{
private int interval; //参数:发布通告的间隔
private boolean beep; //参数:开关铃声的标志 /**
* Constructs a talking clock
* @param interval the interval between messages (in milliseconds)
* @param beep true if the clock should beep
*/
public TalkingClock(int interval, boolean beep)
{
this.interval = interval;
this.beep = beep; //this引用
} /**
* Starts the clock.
*/
public void start() //start方法
{
var listener = new TimePrinter(); //创建TimePrinter对象
var timer = new Timer(interval, listener);
timer.start();
}
//TimePrinter类位于 TalkingClock类内部(内部类访问对象状态:TimePrinter对象由TalkingClock类方法构造)
//定义一个实现ActionListener接口的类
public class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event) //调用actionPerformed方法,并在发出铃声之前检查了beep标志
{
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
}

运行结果:

实验程序2:

  编辑、调试运行教材254页程序6-8,结合程序运行结果理解程序;

  掌握匿名内部类的用法。

6-8源代码:

package anonymousInnerClass;

import java.awt.*;
import java.awt.event.*;
import java.time.*; import javax.swing.*; /**
* This program demonstrates anonymous inner classes.
* @version 1.12 2017-12-14
* @author Cay Horstmann
*/
public class AnonymousInnerClassTest
{
public static void main(String[] args)
{
var clock = new TalkingClock();
clock.start(1000, true); // keep program running until the user selects "OK"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
} /**
* A clock that prints the time in regular intervals.
*/
class TalkingClock
{
/**
* Starts the clock.
* @param interval the interval between messages (in milliseconds)
* @param beep true if the clock should beep
*/
public void start(int interval, boolean beep) //将TalkingClock构造器的参数interval和beep移至start方法中
{
//匿名内部类
//创建一个实现ActionListener接口的类的新对象,需要实现的方法actionPerformed定义在括号{}内
var listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
if (beep) Toolkit.getDefaultToolkit().beep(); //actionPerformed方法执行if (beep)……
}
};
var timer = new Timer(interval, listener);
timer.start();
}
}

运行结果:

实验程序3:

   在elipse IDE中调试运行教材257页-258页程序6-9,结合程序运行结果理解程序;

  了解静态内部类的用法。

6-9源代码:

package staticInnerClass;

/**
* This program demonstrates the use of static inner classes.
* @version 1.02 2015-05-12
* @author Cay Horstmann
*/
public class StaticInnerClassTest
{
public static void main(String[] args)
{
var values = new double[20];
for (int i = 0; i < values.length; i++)
values[i] = 100 * Math.random();
ArrayAlg.Pair p = ArrayAlg.minmax(values); //将Pair定义为ArrayAlg的内部类,通过ArrayAlg.minmax访问
System.out.println("min = " + p.getFirst());
System.out.println("max = " + p.getSecond());
}
} //外部类
class ArrayAlg
{
/**
* A pair of floating-point numbers
*/
public static class Pair //Pair类
{
//两个参数
private double first;
private double second; /**
* Constructs a pair from two floating-point numbers
* @param f the first number
* @param s the second number
*/
public Pair(double f, double s)
{
first = f;
second = s;
} /**
* Returns the first number of the pair
* @return the first number
*/
public double getFirst() //getFirst方法
{
return first;
} /**
* Returns the second number of the pair
* @return the second number
*/
public double getSecond() //getSecond方法
{
return second;
}
} /**
* Computes both the minimum and the maximum of an array
* @param values an array of floating-point numbers
* @return a pair whose first element is the minimum and whose second element
* is the maximum
*/
//静态内部类
public static Pair minmax(double[] values)
{
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (double v : values)
{
if (min > v) min = v;
if (max < v) max = v;
}
return new Pair(min, max);
}
}

运行结果:

实验总结:

  通过本次实验的学习,掌握了接口,Lambda表达式以及内部类的基本知识,对java有了一定的深入了解,但是在实际问题的解决当中依然有问题。编程实验起初不懂得如何着手,仍需要继续努力学习。通过实验结合知识的操作,掌握了些许的Java新知识点,但仍有许多不足之处,需要继续努力学习探究。

最新文章

  1. Android开发拾遗(一)用Wi-Fi连接adb
  2. 手机web站点和手机app 技术选型的困惑于思考
  3. Javascript 去掉字符串前后空格的五种方法
  4. in C#,编译型常量(const)和运行时常量(readonly)
  5. PHP实战开发教程
  6. 微信小应用vs progressive-web-apps
  7. java基础----&gt;String中的split方法的原理
  8. CentOS 6.8 部署django项目一
  9. U3D面试五
  10. Python开源框架、库、软件和资源大集合
  11. Xcode 插件集:xTextHandler
  12. JS的语法
  13. Storm-源码分析- Component ,Executor ,Task之间关系
  14. 将自己的框架更新到cocopods上
  15. TScreen 类
  16. python3将docx转换成pdf,html文件,pdf转doc文件
  17. php中magic_quotes_gpc的作用 解决日文数据提交后多出来反斜杠的问题
  18. user_admin
  19. 如何理解Java程序使用Unicode字符集编写
  20. 使用windos电脑模拟搭建集群(三)实现全网监控

热门文章

  1. 四,专著研读(K-近邻算法)
  2. python copy和deepcopy
  3. 浅谈C++ STL queue 容器
  4. Java 基础系列:不变性
  5. Prometheus神器之监控K8s集群
  6. Python连载22-调试&amp;单元测试
  7. Python 将numpy array由浮点型转换为整型
  8. Module Code: CMT107
  9. LaTex语法
  10. dubbo入门学习