在本文中,我们将给您介绍关于201771010120苏浪浪《面向对象程序设计的详细内容,并且为您解答java》第11周学习总结的相关问题,此外,我们还将为您提供关于201723032017-2018-
在本文中,我们将给您介绍关于201771010120 苏浪浪 《面向对象程序设计的详细内容,并且为您解答java》第11周学习总结的相关问题,此外,我们还将为您提供关于20172303 2017-2018-2 《程序设计与数据结构》第11周学习总结、20175221曾祥杰 第11周学习总结、201771010106 东文财《面向对象程序设计(java)》 实验 6、201771010106 东文财《面向对象程序设计(java)》 实验 8的知识。
本文目录一览:- 201771010120 苏浪浪 《面向对象程序设计(java)》第11周学习总结(java面向对象程序设计苏守宝答案)
- 20172303 2017-2018-2 《程序设计与数据结构》第11周学习总结
- 20175221曾祥杰 第11周学习总结
- 201771010106 东文财《面向对象程序设计(java)》 实验 6
- 201771010106 东文财《面向对象程序设计(java)》 实验 8
201771010120 苏浪浪 《面向对象程序设计(java)》第11周学习总结(java面向对象程序设计苏守宝答案)
实验十一 集合
1、实验目的与要求
(1) 掌握Vetor、Stack、Hashtable三个类的用途及常用API;
(2) 了解java集合框架体系组成;
(3) 掌握ArrayList、LinkList两个类的用途及常用API。
(4) 了解HashSet类、TreeSet类的用途及常用API。
(5)了解HashMap、TreeMap两个类的用途及常用API;
(6) 结对编程(Pair programming)练习,体验程序开发中的两人合作。
2、实验内容和步骤
实验1: 导入第9章示例程序,测试程序并进行代码注释。
测试程序1:
l 使用JDK命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;
l 掌握Vetor、Stack、Hashtable三个类的用途及常用API。
//示例程序1 import java.util.Vector;
class Cat { private int catNumber;
Cat(int i) { catNumber = i; }
void print() { System.out.println("Cat #" + catNumber); } }
class Dog { private int dogNumber;
Dog(int i) { dogNumber = i; }
void print() { System.out.println("Dog #" + dogNumber); } }
public class CatsAndDogs { public static void main(String[] args) { Vector cats = new Vector(); for (int i = 0; i < 7; i++) cats.addElement(new Cat(i)); cats.addElement(new Dog(7)); for (int i = 0; i < cats.size(); i++) ((Cat) cats.elementAt(i)).print(); } } |
//示例程序2 import java.util.*;
public class Stacks { static String[] months = { "1", "2", "3", "4" };
public static void main(String[] args) { Stack stk = new Stack(); for (int i = 0; i < months.length; i++) stk.push(months[i]); System.out.println(stk); System.out.println("element 2=" + stk.elementAt(2)); while (!stk.empty()) System.out.println(stk.pop()); } } |
//示例程序3 import java.util.*;
class Counter { int i = 1;
public String toString() { return Integer.toString(i); } }
public class Statistics { public static void main(String[] args) { Hashtable ht = new Hashtable(); for (int i = 0; i < 10000; i++) { Integer r = new Integer((int) (Math.random() * 20)); if (ht.containsKey(r)) ((Counter) ht.get(r)).i++; else ht.put(r, new Counter()); } System.out.println(ht); } } |
1
package a;
import java.util.Vector;
class Cat {
private int catNumber;
Cat(int i) {
catNumber = i;
}
void print() {
System.out.println("Cat #" + catNumber);
}
}
class Dog {
private int dogNumber;
Dog(int i) {
dogNumber = i;
}
void print() {
System.out.println("Dog #" + dogNumber);
}
}
public class CatsAndDogs {
public static void main(String[] args) {
Vector cats = new Vector();
Vector dogs = new Vector();
for (int i = 0; i < 7; i++)
cats.addElement(new Cat(i));
cats.addElement(new Dog(7));
for (int i = 0; i < cats.size(); i++)
if(cats.elementAt(i)instanceof Cat)//做出判断能否被转换
{
((Cat) cats.elementAt(i)).print();
}
else
((Dog) cats.elementAt(i)).print();
}
}
2
package b;
import java.util.*;
public class Stacks {//stack是java里的一个集合类,用于模拟一个堆栈,存放的信息是后进的元素先出
static String[] months = { "1", "2", "3", "4" };
public static void main(String[] args) {
Stack stk = new Stack();
for (int i = 0; i < months.length; i++)
stk.push(months[i]);
System.out.println(stk);
System.out.println("element 2=" + stk.elementAt(2));
while (!stk.empty())
System.out.println(stk.pop());
}
}
3
package c;
import java.util.*;
class Counter {
int i = 1;
public String toString() {
return Integer.toString(i);
}
}
public class Statistics {
public static void main(String[] args) {
Hashtable ht = new Hashtable();//相当于array,里面可以存放大多数类型数据,在不知array的情况下用hashtable 比较方便;(键值类)
for (int i = 0; i < 10000; i++) {
Integer r = new Integer((int) (Math.random() * 20));//生成20以内的随机数
if (ht.containsKey(r))//Hashtable常用方法,判断r是不是键值的一个方法
((Counter) ht.get(r)).i++;
else
ht.put(r, new Counter());
}
System.out.println(ht);
}
}
测试程序2:
l 使用JDK命令编辑运行ArrayListDemo和LinkedListDemo两个程序,结合程序运行结果理解程序;
import java.util.*;
public class ArrayListDemo { public static void main(String[] argv) { ArrayList al = new ArrayList(); // Add lots of elements to the ArrayList... al.add(new Integer(11)); al.add(new Integer(12)); al.add(new Integer(13)); al.add(new String("hello")); // First print them out using a for loop. System.out.println("Retrieving by index:"); for (int i = 0; i < al.size(); i++) { System.out.println("Element " + i + " = " + al.get(i)); } } } |
import java.util.*; public class LinkedListDemo { public static void main(String[] argv) { LinkedList l = new LinkedList(); l.add(new Object()); l.add("Hello"); l.add("zhangsan"); ListIterator li = l.listIterator(0); while (li.hasNext()) System.out.println(li.next()); if (l.indexOf("Hello") < 0) System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } } |
package b;
import java.util.*;
public class ArrayListDemo {
public static void main(String[] argv) {
ArrayList al = new ArrayList();//ArrayList是实现了基于动态数组的数据结构;ArrayList要移动数据.
// Add lots of elements to the ArrayList...
al.add(new Integer(11));
al.add(new Integer(12));
al.add(new Integer(13));
al.add(new String("hello"));
// First print them out using a for loop.
System.out.println("Retrieving by index:");
for (int i = 0; i < al.size(); i++) {
System.out.println("Element " + i + " = " + al.get(i));
}
}
}
2
package cc;
import java.util.*;
public class LinkedListDemo {
public static void main(String[] argv) {
LinkedList l = new LinkedList();//LinkedList基于链表的数据结构;LinkedList要移动指针
l.add(new Object());
l.add("Hello");
l.add("zhangsan");
ListIterator li = l.listIterator(0);
while (li.hasNext())
System.out.println(li.next());
if (l.indexOf("Hello") < 0)
System.err.println("Lookup does not work");
else
System.err.println("Lookup works");
}
}
l 在Elipse环境下编辑运行调试教材360页程序9-1,结合程序运行结果理解程序;
l 掌握ArrayList、LinkList两个类的用途及常用API。
package linkedList;
import java.util.*;
/**
* This program demonstrates operations on linked lists.
* @version 1.11 2012-01-26
* @author Cay Horstmann
*/
public class LinkedListTest//LinkedList基于链表的数据结构;LinkedList要移动指针
{
public static void main(String[] args)
{
List<String> a = new LinkedList<>();
a.add("Amy");
a.add("Carl");
a.add("Erica");
List<String> b = new LinkedList<>();
b.add("Bob");
b.add("Doug");
b.add("Frances");
b.add("Gloria");
// merge the words from b into a
ListIterator<String> aIter = a.listIterator();
Iterator<String> bIter = b.iterator();
while (bIter.hasNext())
{
if (aIter.hasNext()) aIter.next();
aIter.add(bIter.next());
}
System.out.println(a);
// remove every second word from b
bIter = b.iterator();
while (bIter.hasNext())
{
bIter.next(); // skip one element
if (bIter.hasNext())
{
bIter.next(); // skip next element
bIter.remove(); // remove that element
}
}
System.out.println(b);
// bulk operation: remove all words in b from a
a.removeAll(b);
System.out.println(a);
}
}
测试程序3:
l 运行SetDemo程序,结合运行结果理解程序;
import java.util.*; public class SetDemo { public static void main(String[] argv) { HashSet h = new HashSet(); //也可以 Set h=new HashSet() h.add("One"); h.add("Two"); h.add("One"); // DUPLICATE h.add("Three"); Iterator it = h.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } |
l 在Elipse环境下调试教材365页程序9-2,结合运行结果理解程序;了解HashSet类的用途及常用API。
package set;
import java.util.*;
/**
* This program uses a set to print all unique words in System.in.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class SetTest
{
public static void main(String[] args)
{
Set<String> words = new HashSet<>(); // HashSet是实现Set接口的一个类,
long totalTime = 0;
try (Scanner in = new Scanner(System.in))
{
while (in.hasNext())
{
String word = in.next();
long callTime = System.currentTimeMillis();
words.add(word);
callTime = System.currentTimeMillis() - callTime;
totalTime += callTime;
}
}
Iterator<String> iter = words.iterator();
for (int i = 1; i <= 20 && iter.hasNext(); i++)
System.out.println(iter.next());
System.out.println(". . .");
System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
}
}
l 在Elipse环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API。
package treeSet;
import java.util.*;
/**
* This program sorts a set of item by comparing their descriptions.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class TreeSetTest//TreeSet的存储原理:底层是通过二叉树的数据结构实现的,存储规则:左小右大,当添加元素的时候依靠的是元素的comparable方法来添加元素
{
public static void main(String[] args)
{
SortedSet<Item> parts = new TreeSet<>();
parts.add(new Item("Toaster", 1234));
parts.add(new Item("Widget", 4562));
parts.add(new Item("Modem", 9912));
System.out.println(parts);
NavigableSet<Item> sortByDescription = new TreeSet<>(
Comparator.comparing(Item::getDescription));
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
测试程序4:
l 使用JDK命令运行HashMapDemo程序,结合程序运行结果理解程序;
import java.util.*; public class HashMapDemo { public static void main(String[] argv) { HashMap h = new HashMap(); // The hash maps from company name to address. h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Sun", "Mountain View, CA"); String queryString = "Adobe"; String resultString = (String)h.get(queryString); System.out.println("They are located in: " + resultString); } } |
package treeSet;
import java.util.*;
public class HashMapDemo {
public static void main(String[] argv) {
HashMap h = new HashMap();//HashMap通过hashcode对其内容进行快速查找
// The hash maps from company name to address.
h.put("Adobe", "Mountain View, CA");
h.put("IBM", "White Plains, NY");
h.put("Sun", "Mountain View, CA");
String queryString = "Adobe";
String resultString = (String)h.get(queryString);
System.out.println("They are located in: " + resultString);
}
}
l 在Elipse环境下调试教材373页程序9-6,结合程序运行结果理解程序;
package map;
import java.util.*;
/**
* This program demonstrates the use of a map with key type String and value type Employee.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class MapTest
{
public static void main(String[] args)
{
Map<String, Employee> staff = new HashMap<>();//HashMap通过hashcode对其内容进行快速查找
staff.put("144-25-5464", new Employee("Amy Lee"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));
// print all entries
System.out.println(staff);
// remove an entry
staff.remove("567-24-2546");
// replace an entry
staff.put("456-62-5527", new Employee("Francesca Miller"));
// look up a value
System.out.println(staff.get("157-62-7935"));
// iterate through all entries
staff.forEach((k, v) ->
System.out.println("key=" + k + ", value=" + v));
}
}
l 了解HashMap、TreeMap两个类的用途及常用API。
:HashMap通过hashcode对其内容进行快速查找,而 TreeMap中所有的元素都保持着某种固定的顺序,如果你需要得到一个有序的结果你就应该使用TreeMap(HashMap中元素的排列顺序是不固定的)。
实验2:结对编程练习:
l 关于结对编程:以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序。
l 关于结对编程的阐述可参见以下链接:
http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html
http://en.wikipedia.org/wiki/Pair_programming
l 对于结对编程中代码设计规范的要求参考:
http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html
以下实验,就让我们来体验一下结对编程的魅力。
l 确定本次实验结对编程合作伙伴;
合作伙伴:马兴德(201771010117);
l 各自运行合作伙伴实验九编程练习1,结合使用体验对所运行程序提出完善建议;
建议:
//修改后: File file = new File("身份证号.txt");(将文件放入该包中更好如前代码—);
package Test;
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{
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("D:\\身份证号.txt");
//修改后: File file = new File("身份证号.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();
}
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("e.退出");
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 "e":
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;
}
}
package Test;
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) {
// int a = Integer.parseInt(age);
this.age= age;
}
public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
}
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
}
public String toString() {
return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
}
}
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
建议:
1)、
(2)、
前边用了该程序以后后边子类不需要定义(b!=0)如上边1)和2)中:(2)明显多余;
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
package Test;
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{
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("身份证号.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();
}
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("e.退出");
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 "e":
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;
}
}
package Test;
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) {
// int a = Integer.parseInt(age);
this.age= age;
}
public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
}
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
}
public String toString() {
return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
}
}
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习2。
package d;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Suanfa counter=new Suanfa();
PrintWriter out = null;
try {
out = new PrintWriter("text.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
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 m= (int) Math.round(Math.random() * 3);
switch(m)
{
case 0:
System.out.println(a + "+" + b + "=");
int d0 = in.nextInt();
out.println(a + "+" + b + "=" + d0);
if (d0 == counter.suanfa1(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();
out.println(a + "-" + b + "=" + d1);
if (d1 == counter.suanfa2(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 2:
System.out.println(a + "*" + b + "=");
int d2 = in.nextInt();
out.println(a + "*" + b + "=" + d2);
if (d2 ==counter.suanfa3(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();
out.println(a + "/" + b + "=" + d3);
if (d3 == counter.suanfa4(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
}
}
System.out.println("成绩"+sum);
out.println("成绩:"+sum);
out.close();
}
}
package d;
public class Suanfa<T> {
private T a;
private T b;
public Suanfa() {
a = null;
b = null;
}
public Suanfa(T a, T b) {
this.a = a;
this.b = b;
}
public int suanfa1(int a,int b)
{
return a+b;
}
public int suanfa2(int a,int b)
{
return a-b;
}
public int suanfa3(int a,int b)
{
return a*b;
}
public int suanfa4(int a,int b)
{
if(b!=0)
return a/b;
else return 0;
}
}
实验总结:通过本周学习以及老师和助教的帮助下:了解了HashMap、TreeMap两个类的用途;学习到了Vetor、Stack、Hashtable三个类的用途; 了解了java集合框架体系组成; 了解了HashSet类、TreeSet类的用途;在结对编程练习的过程中,我前边程序的不足得到一些完善;也了解到结对练习的好处。
20172303 2017-2018-2 《程序设计与数据结构》第11周学习总结
20172303 2017-2018-2 《程序设计与数据结构》第11周学习总结
教材学习内容总结
第23章 Android简介
1.组件
Android应用程序组件共有四种:
- 活动(Activity):用户交互的窗口。
- 服务(Service):在后台长时间运行的操作。
- 广播接受者(Broadcast receiver):一个监听器。
- 内容提供者(Content provider):管理要和其他程序分享数据的一个组件。
2.意图
- 意图(intent)是Android程序中的一条消息,用于要求程序执行某一动作。
3.清单
- 每个应用程序都必须包含一个XML形式的清单(manifest),其中应该包含以下几项:
- 程序所需的最小的API Level
- 程序的名称
- 用户在触碰应用程序图标时打开的第一个活动窗口
- 是否允许其他应用程序调用该程序的组件
- 用户需保证的许可
第24章 初识Android
一、应用程序的调试
- 1.日志
- 使用日志消息是最简单的调试应用程序的方法,Android中使用
android.util.Log
来记录日志消息。
- 使用日志消息是最简单的调试应用程序的方法,Android中使用
- 2.设置断点
- 在某一行单击,选择
Run→Toggle Line Breakpoint
即可设置断点。或在某一行代码的侧边栏单机也可设置断点。 - 使用
Run→Debug
来调试
- 在某一行单击,选择
二、应用程序结构
- Project窗口中主要有两个节点————app和Gradle Scripts。
- Gradle Scripts节点包含了Gradle构件脚本。
- app节点包含了manifests、java和res三个节点。
第25章 活动
1.活动的生命周期
onCreate()
:这个方法会在活动第一次被创建的时候被调用。这个方法用于对活动的初始化,如加载布局,绑定事件等。onStart()
:这个方法在活动由不可见到可见时被调用。onResume()
:这个方法在活动准备好和用户进行交互的时候被调用。onPause()
:这个方法在系统准备去启动或恢复另一个活动时被调用。(我们通常会在这个方法中将一些消耗CPU的资源释放掉,以及保存一些关键数据,但这个方法的执行速度一定要快,否则会影响到新的栈顶活动的使用)onStop()
:这个方法在活动完全不可见的时候调用。它和onPause()方法
的主要区别在于,如果启动的新活动是一个对话框式的活动,那么onPause()方法
会得到执行,而onStop()方法
并不会执行。onDestroy()
:这个方法在活动被销毁之前调用。之后的活动状态变为销毁状态。onRestart()
:这个方法在活动由停止状态变为运行状态之前调用,也就是活动被重新启动了。
2.修改应用程序图标
- 在
res/drawable
中保存一个jepg或png文件 - 编辑manifest中的android:icon属性,使用
@drawable/图像文件名称
来引用图像。
第26章 UI组件
- Android提供了许多的UI组件,你能按需构建应用的用户交互界面
- TextView:文本标签
- EditText:文本框,是TextView的一个子类,有副文本编辑能力
- Button:按钮,可以按压、点击,由用户完成一个动作
- ImageButton:图片按钮
- CheckBox:复选框,可以作为用户使用的一个开关。当有一系列可供选择的选项时,可使用该控件
- ToggleButton:带有一个“灯泡亮暗”效果的开关按钮
- Spinner:下拉列表,允许用户在多个选项中选择一个
- TimePicker:时间选择器,能让用户输入时间,有12小时和24小时模式
- DatePicker:日期选择器,能让用户输入日期
- ProgressBar:进度条,为用户提供某项工作的进度,比如后台正在做的事情
教材学习中的问题和解决过程
- 问题1:R类究竟是什么?
- 问题1解决方案:刚开始翻书的时候不认真,后来在书上P254发现了解释:R类是AS中看不到的一个通用类,可以在
app/build/generated/source
目录下找到它。每当添加、修改或者删除资源时,都会重新生成R。R的作用是让你可以在代码中引用一个资源。 - 问题2:在看书的时候,对活动程序的结构还是很模糊
- 问题2解决方案:在自己真正建了一个程序之后就比较清楚了。
- build:该目录包含了自动生成的文件,这些文件包括了编译设置项、R类等
- libs:该目录包含了开发Android应用所需要的库文件
- src:该目录存放了应用的源代码.java文件。默认情况下,它包含了MainActivity.java文件,这个源代码j有一部分是执行了你点击应用图标时启动应用所需要功能
- res:该目录存放了所有的资源文件
- drawable:该目录存放了项目的drawable对象和一些图片资源
- layout:该目录存放了各个界面的布局文件
- menu:该目录存放了应用中设计的菜单对象
- mipmap:该目录存放了应用的主要图片资源
- values:该目录存放了字符串、颜色等定义的资源集合
- AndroidManifest.xml:该文件是描述应用基础特性的文件,定义了每个组件。
- res:该目录存放了所有的资源文件
- 问题3:对于程序的生命活动周期,有没有什么具体易懂的简单例子?
- 问题3解决方法:找到一篇博客android 活动的生命周期 ,里面举的例子就非常好,除此之外,博客里还把整个活动周期分成三个部分:
- 完整生存期:onCreate()方法和onDestroy()之间,总共调用了6个方法。
- 可见生存期:活动在onStart()方法和onStop()之间,总共4个方法,再加上重新运行的onRestart()方法,总共5个。
- 前台生存期:活动在onResume()方法和onPause()方法,总共2个方法。
代码调试中的问题和解决过程
- 问题1:刚刚下载好AS的时候,提示:
- 问题1解决方法:以管理员的身份打开cmd,在里面输入
netsh winsock reset
后重启即可。 - 问题2:提示错误
Error:Failed to find target with hash string ''android-27'' in: E:\androidstudio\androidstudio\sdk
- 问题2解决方法:产生该错误的原因是所需的编译版本缺失,解决方法是打开
build.gradle
文件,将里面相应的版本降低下来即可。 - 问题3:提示错误
Error:(11) error: attribute ''android:roundIcon'' not found.
- 问题3解决方法:删除AndroidManifest.xml里的
android:roundIcon="@mipmap/ic_launcher_roun
即可 - 问题4:在使用git push的时候提示失败,按教程用git pull还是提示失败
- 问题4解决方法:失败的原因是码云上的东西和本地的东西有差别,所以不管是pull还push都会有问题。解决的方法是重新建一个项目,在建项目的时候取消勾选“使用Readme文件初始化这个项目”,
之后就没有什么问题了。
代码托管
上周考试错题总结(正确为绿色,错误为红色)
- 错题1:Abstract Data Types have which of the following object-oriented features?
- <span>A .information hiding
- <span>B .inheritance
- C .polymorphism
- D .message passing
- E .all of the above
- 原因及理解情况:抽象类数据类型既封装了数据结构又封装了操作数据结构的方法,所以可以隐藏信息。因此,所有ADT都利用信息隐藏功能,以便数据结构不能直接从ADT外部操作,但不需要其他面向对象的功能。
- 错题2:A simple linear list
- <span>A .is an example of a degenerate tree
- B .is an example of a degenerate graph
- C .is an example of a degenerate digraph
- <span>D .cannot be represented as a degenerate tree, graph or digraph
- E .none of the above
- 原因及理解情况:看题的时候没有注意degenerate,觉得图和树都是非线性结构就选了D,但其实退化了的树结构只有一个分支,就相当于一个简单的线性结构。
- 问题3:在Ubuntu中,使用vim编辑器时,想要移动光标,除方向键之外,还可以依次使用hjkl键进行上下左右的移动。
- <span>A .true
- <span>B .false
- 原因及理解情况:上下左右顺序依次是kjhl,当时做题的时候只关注了是不是这几个字母,没想到还要一一对应,太坑了_(:з」∠)_
- 问题4:在Linux Bash中,为所有人对file1.txt文件添加写入权限的命令是chmod o+w filel.txt 或者 chmod 666 filel.txt.
- <span>A .true
- <span>B .false
- 原因及理解情况:chmod a+w filel.txt是给所有人加上可写权限,包括所有者,所属组,和其他人。chmod o+w filel.txt是只给其他人加上可写权限。
结对及互评
点评模板:
- 博客中值得学习的或问题:
- 优点:从本周的博客中可以很明显地看出整个学习历程
- 问题:教材学习内容列的有些杂乱,可以采用分点的方式来写。
- 代码中值得学习的或问题:
- 本周的代码基本都是直接拷进去的,大家的代码都比较类似。基本没有问题。
点评过的同学博客和代码
- 本周结对学习情况
- 20172322
- 结对学习内容
- 张昊然同学教会了我如何往AS里放代码,在下AS的初期帮我解决了一些错误。
其他(感悟、思考等,可选)
- 没想到在学期的期末还会接触到这么难啃的一块骨头,刚开始学的时候真的是懵的,而且走的很艰难,幸亏这周三做了那几个实验,使我对这部分的知识更加清楚了。不过每一次打开虚拟机还是很有成就感的,现在我也是能做简单APP的人了!
学习进度条
代码行数(新增/累积) | 博客量(新增/累积) | 学习时间(新增/累积) | 重要成长 | |
---|---|---|---|---|
目标 | 5000行 | 30篇 | 400小时 | |
第一周 | 120/120 | 1/1 | 9/9 | |
第二周 | 246/366 | 1/2 | 9/18 | |
第三周 | 785/1121 | 2/4 | 15/33 | |
第四周 | 615/1736 | 1/5 | 20/53 | |
第五周 | 1409/2645 | 1/6 | 24/77 | |
第六周 | 561/3206 | 1/7 | 20/97 | 再次搞清了一些自己有点含糊不清的概念 |
第七周 | 63/3269 | 1/8 | 15/112 | |
第八周 | 2476/5745 | 3/11 | 90/201 | |
第九周 | 824/6595 | 1/12 | 20/221 | |
第十周 | 919/7514 | 2/14 | 20/241 | |
第十一周 | 0/7514 | 3/17 | 40/281 |
- 计划学习时间:20小时
- 实际学习时间:40小时
- 改进情况:本周很大一部分时间花在了安装AS上,这个东西真的...当最后真的把它装好,所有的程序都显示绿色的OK时,不禁有种想要热泪盈眶的感觉
参考资料
- 《Java程序设计与数据结构教程(第二版)》
- 《Java程序设计与数据结构教程(第二版)》学习指导
- android studio 配置+安装
- android 活动的生命周期
- android studio学习
- Error:Failed to find target with hash string ''android-25'' in: E:\androidstudio\androidstudio\sdk
20175221曾祥杰 第11周学习总结
20175221 《Java程序设计》第11周学习总结
教材学习内容总结
第13章主要内容:
-
URL类
- 一个URL对象通常包含最基本的三部分信息:协议、地址、资源。
- URL的构造方法:
- public URL(String spec) throws MalformedURLException
- public URL(String protocol String host,String file) throws MalformedULRException
- 调用 InputStream openStream() 方法可以返回一个输入流,该输入流指向URL对象所包含的资源,通过该输入流可以将服务器上的资源读入客户端。
-
InetAdress类
-
获取主机地址:
- 使用InetAddress类的静态方法: getByName(String s) 获取包含主机地址的域名和IP地址的对象
-
获取本地机地址:
- 使用InetAddress类的静态方法: getLocalHost() 获得含本机域名和IP地址的对象
-
套接字
- 客户端套接字对象: Socket mysocket=new Socket
- 调用方法获得一个输入/输出流: getInputStream() / getOutputStream()
- 服务器端套接字对象: ServerSocket serverForClient =new ServerSocket()
- 使用 accept() 接收套接字连接,使用 close() 关闭套接字连接
-
UDP数据报
-
UDP通信的基本模式是:
- 将数据打包,称为数据包,然后将数据包发往目的地。
- 接受别人发来的数据包,然后查看数据包中的内容。
-
广播数据报
- 广播端和接受端应加入到相同D类IP地址的相同port端口
- 调用 socket.joinGroup(group) 加入相同地址
-
Java 远程调用(RMI)
- 扩展Remote接口
- 创建远程对象的类
- 存根与代理:RMI使用rmic命令生成存根
- 远程服务器注册执行 rimregistry 命令
- 启动远程对象服务:先创建一个远程对象,然后调用方法 rebind(String name, Remote obj)
代码调试中的问题和解决过程
- 问题1:在完成选做作业:简易计算器(选做)时,发现在IDEA里,直接 run 每次都提示老师开始给的那行报错
-
问题1解决方案:
- 在命令行中编译后,执行 java 文件 op1 符号 op2 即可
代码托管
statistics.sh脚本的运行结果截图
上周考试错题总结
无
学习进度条(五月份继)
代码行数(新增/累积) | 博客量(新增/累积) | 学习时间(新增/累积) | 重要成长 | |
---|---|---|---|---|
目标 | 5000行 | 8篇 | 100小时 | |
第一周 | 13/13 | 4/4 | 12/12 | |
第二周 | 309/322 | 1/5 | 13/25 | |
第三周 | 614/923 | 1/6 | 15/40 | |
第四周 | 384/1379 | 2/8 | 12/52 | |
第五周 | 565/1954 | 1/9 | 12/64 | |
第六周 | 1080/3034 | 4/13 | 15/79 | |
第七周 | 671/3705 | 2/15 | 12/91 | |
第八周 | 597/4302 | 3/18 | 12/103 | |
第九周 | 1533/5238 | 4/22 | 12/115 | |
第十周 | 841/6043 | 4/26 | 15/130 | |
第十一周 | 988/7031 | 1/27 | 15/145 |
尝试一下记录「计划学习时间」和「实际学习时间」,到期末看看能不能改进自己的计划能力。这个工作学习中很重要,也很有用。 耗时估计的公式 :Y=X+X/N ,Y=X-X/N,训练次数多了,X、Y就接近了。
参考:软件工程软件的估计为什么这么难,软件工程 估计方法
-
计划学习时间:12
-
实际学习时间:15
-
改进情况:继续保持稳定前进
(有空多看看现代软件工程 课件软件工程师能力自我评价表)
参考资料
-
Java学习笔记(第8版)
-
《Java学习笔记(第8版)》学习指导
-
[ Java 2 实用教程(第5版)]
201771010106 东文财《面向对象程序设计(java)》 实验 6
实验六继承定义与使用
实验时间 2018-9-28
一。知识总结
1、继承的概述:在多个类中存在相同的属性和行为,把这些相同的部分抽取到一个单独的类中,把这个单独的类叫作父类,也叫基类或者超类,把其他被抽取的类叫作子类,并且父类的所有属性和方法(除 private 修饰的私有属性和方法外),子类都可以调用。这样的一种行为就叫做继承。(相同的东西在父类,不同的东西在子类)
2、继承的关键字:extends
3、继承的格式:class 子类名 extends 父类名 { }
4、在代码中使用继承提高了代码的复用性和维护性,让类与类直接产生了关系。
5、继承的注意点:
①子类只能继承父类所有的非私有的成员方法和成员变量,private 修饰的不能继承。
②子类不能继承父类的构造方法,但可以通过 super 关键字去访问父类的构造方法。(先初始化父类,再执行自己)
③不同包不能继承。
6、在使用 super 的时候,我们还需要了解关键字 super 和 this 的区别:
super :到父类中去找方法,没有引用的作用;也可以用于其他方法中;与 this 调用构造方的重载一样,用于第一行。
this:是指当前正在初始化的这个对象的引用。
二。实验部分:
1、实验目的与要求
(1) 理解继承的定义;
(2) 掌握子类的定义要求
(3) 掌握多态性的概念及用法;
(4) 掌握抽象类的定义及用途;
(5) 掌握类中 4 个成员访问权限修饰符的用途;
(6) 掌握抽象类的定义方法及用途;
(7) 掌握 Object 类的用途及常用 API;
(8) 掌握 ArrayList 类的定义方法及用法;
(9) 掌握枚举类定义方法及用途。
2、实验内容和步骤
实验 1: 导入第 5 章示例程序,测试并进行代码注释。
测试程序 1:
在 elipse IDE 中编辑、调试、运行程序 5-1 (教材 152 页 - 153 页) ;
掌握子类的定义及用法;
结合程序运行结果,理解并总结 OO 风格程序构造特点,理解 Employee 和 Manager 类的关系子类的用途,并在代码中添加注释。
package inheritance;
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 inheritance;
public class Manager extends Employee
//关键字extends表示继承。表明正在构造一个新类派生于一个已经存在的类。已经存在的类称为超类/基类/或者父类;新类称为子类/派生类/或者孩子类。
{
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);
//调用超类中含有n,s,year,month,day参数的构造器
bonus = 0;
}
public double getSalary()
//子类要想访问要想访问超类中的方法需要使用特定的关键字super,
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
}
package inheritance;
/**
* This program demonstrates inheritance.
* @version 1.21 2004-02-21
* @author Cay Horstmann
*/
public class ManagerTest
{
public static void main(String[] args)
{
// 构建管理者对象
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[3];
// 用管理者和雇员对象填充工作人员数组
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
// 打印所有员工对象的信息
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}
实验结果:
测试程序 2:
编辑、编译、调试运行教材 PersonTest 程序(教材 163 页 - 165 页);
掌握超类的定义及其使用要求;
掌握利用超类扩展子类的要求;
在程序中相关代码处添加新知识的注释。
package abstractClasses;
import java.time.*;
public class Employee extends Person
{
private double salary;
private LocalDate hireDay;
public Employee(String name, double salary, int year, int month, int day)
{
super(name);
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public double getSalary()
{
return salary;
}
public LocalDate getHireDay()
{
return hireDay;
}
//重写父类方法,返回一个格式化的字符串
public String getDescription()
{
return String.format("an employee with a salary of $%.2f", salary);
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
}
package abstractClasses;
public abstract class Person
{
//包含一个或多个抽象方法的类被称为抽象类,由abstract关键字修饰
public abstract String getDescription();
private String name;
public Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
package abstractClasses;
/**
* This program demonstrates abstract classes.
* @version 1.01 2004-02-21
* @author Cay Horstmann
*/
public class PersonTest
{
public static void main(String[] args)
{
//抽象类的声明,但不能将抽象类实例化 ,实例化的是Person类的子类
Person[] people = new Person[2];
// 用学生和雇员填充人物数组
people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
people[1] = new Student("Maria Morris", "computer science");
// 打印所有人对象的名称和描述 for (Person p : people)
System.out.println(p.getName() + ", " + p.getDescription());
}
}
package abstractClasses;
public class Student extends Person
{
private String major;
/**
* @param nama the student''s name
* @param major the student''s major
*/
public Student(String name, String major)
{
// 通过n to 总纲构造函数
super(name);
this.major = major;
}
public String getDescription()
{
return "a student majoring in " + major;
}
}
实验结果:
测试程序 3:
编辑、编译、调试运行教材程序 5-8、5-9、5-10,结合程序运行结果理解程序(教材 174 页 - 177 页);
掌握 Object 类的定义及用法;
在程序中相关代码处添加新知识的注释。
package equals;
import java.time.*;
import java.util.Objects;
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;
}
public boolean equals(Object otherObject)
{
//这里获得一个对象参数,第一个if语句判断两个引用是否是同一个,如果是那么这两个对象肯定相等
if (this == otherObject) return true;
// 如果显式参数为空,则必须返回false
if (otherObject == null) return false;
// if the classes don''t match, they can''t be equal
if (getClass() != otherObject.getClass()) return false;
// 现在我们知道另一个对象是非空雇员
Employee other = (Employee) otherObject;
// test whether the fields have identical values
return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
}
public int hashCode()
{
return Objects.hash(name, salary, hireDay);
}
public String toString()// toString()方法
{
return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
+ "]";
}
}
package equals;
/**
* This program demonstrates the equals method.
* @version 1.12 2012-01-26
* @author Cay Horstmann
*/
public class EqualsTest
{
public static void main(String[] args)
{
Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
Employee alice2 = alice1;
Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
System.out.println("alice1 == alice2: " + (alice1 == alice2));
System.out.println("alice1 == alice3: " + (alice1 == alice3));
System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));
System.out.println("alice1.equals(bob): " + alice1.equals(bob));
System.out.println("bob.toString(): " + bob);
Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
System.out.println("boss.toString(): " + boss);
System.out.println("carl.equals(boss): " + carl.equals(boss));
System.out.println("alice1.hashCode(): " + alice1.hashCode());
System.out.println("alice3.hashCode(): " + alice3.hashCode());
System.out.println("bob.hashCode(): " + bob.hashCode());
System.out.println("carl.hashCode(): " + carl.hashCode());
}
}
package equals;
public class Manager extends Employee
{
private double bonus;
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 bonus)
{
this.bonus = bonus;
}
public boolean equals(Object otherObject)
{
if (!super.equals(otherObject)) return false;
Manager other = (Manager) otherObject;
// 检查这个和其他属于同一个类
return bonus == other.bonus;
}
public int hashCode()
{
return java.util.Objects.hash(super.hashCode(), bonus);
}
public String toString()
{
return super.toString() + "[bonus=" + bonus + "]";
}
}
实验结果:
测试程序 4:
在 elipse IDE 中调试运行程序 5-11(教材 182 页),结合程序运行结果理解程序;
掌握 ArrayList 类的定义及用法;
在程序中相关代码处添加新知识的注释。
package arrayList;
import java.util.*;
/**
* This program demonstrates the ArrayList class.
* @version 1.11 2012-01-26
* @author Cay Horstmann
*/
public class ArrayListTest
{
public static void main(String[] args)
{
// 用三个雇员对象填充工作人员数组列表
ArrayList<Employee> staff = new ArrayList<>();
staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
//把每个人的薪水提高5%
for (Employee e : staff)
e.raiseSalary(5);
// 打印所有员工对象的信息
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
+ e.getHireDay());
}
}
package arrayList;
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;
}
}
实验结果:
测试程序 5:
编辑、编译、调试运行程序 5-12(教材 189 页),结合运行结果理解程序;
掌握枚举类的定义及用法;
在程序中相关代码处添加新知识的注释。
package enums;
import java.util.*;
/**
* This program demonstrates enumerated types.
* @version 1.0 2004-05-24
* @author Cay Horstmann
*/
public class EnumTest
{
private static Scanner in;
public static void main(String[] args)
{
in = new Scanner(System.in);
System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
String input = in.next().toUpperCase();
Size size = Enum.valueOf(Size.class, input);
System.out.println("size=" + size);
System.out.println("abbreviation=" + size.getAbbreviation());
if (size == Size.EXTRA_LARGE)
System.out.println("Good job--you paid attention to the _.");
}
}
enum Size
{
SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
private Size(String abbreviation) { this.abbreviation = abbreviation; }
public String getAbbreviation() { return abbreviation; }
private String abbreviation;
}
实验结果:
实验 2:编程练习 1
定义抽象类 Shape:
属性:不可变常量 double PI,值为 3.14;
方法:public double getPerimeter ();public double getArea ())。
让 Rectangle 与 Circle 继承自 Shape 类。
编写 double sumAllArea 方法输出形状数组中的面积和和 double sumAllPerimeter 方法输出形状数组中的周长和。
main 方法中
1)输入整型值 n,然后建立 n 个不同的形状。如果输入 rect,则再输入长和宽。如果输入 cir,则再输入半径。
2) 然后输出所有的形状的周长之和,面积之和。并将所有的形状信息以样例的格式输出。
3) 最后输出每个形状的类型与父类型,使用类似 shape.getClass ()(获得类型),shape.getClass ().getSuperclass ()(获得父类型);
思考 sumAllArea 和 sumAllPerimeter 方法放在哪个类中更合适?
输入样例:
3
rect
1 1
rect
2 2
cir
1
输出样例:
18.28
8.14
[Rectangle [width=1, length=1], Rectangle [width=2, length=2], Circle [radius=1]]
class Rectangle,class Shape
class Rectangle,class Shape
class Circle,class Shape
package shape;
import java.math.*;
import java.util.*;
import shape.shape;
import shape.Rectangle;
import shape.Circle;
public class shapecount
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String rect = "rect";
String cir = "cir";
System.out.print("请输入形状个数:");
int n = in.nextInt();
shape[] score = new shape[n];
for(int i=0;i<n;i++)
{
System.out.println("请输入形状类型 (rect or cir):");
String input = in.next();
if(input.equals(rect))
{
double length = in.nextDouble();
double width = in.nextDouble();
System.out.println("Rectangle["+"length:"+length+" width:"+width+"]");
score[i] = new Rectangle(width,length);
}
if(input.equals(cir))
{
double radius = in.nextDouble();
System.out.println("Circle["+"radius:"+radius+"]");
score[i] = new Circle(radius);
}
}
shapecount c = new shapecount();
System.out.println(c.sumAllPerimeter(score));
System.out.println(c.sumAllArea(score));
for(shape s:score)
{
System.out.println(s.getClass()+", "+s.getClass().getSuperclass());
}
}
public double sumAllArea(shape score[])
{
double sum = 0;
for(int i = 0;i<score.length;i++)
sum+= score[i].getArea();
return sum;
}
public double sumAllPerimeter(shape score[])
{
double sum = 0;
for(int i = 0;i<score.length;i++)
sum+= score[i].getPerimeter();
return sum;
}
}
package shape;
public class Rectangle extends shape
{
private double width;
private double length;
public Rectangle(double w,double l)
{
this.width = w;
this.length = l;
}
public double getPerimeter()
{
double Perimeter = (width+length)*2;
return Perimeter;
}
public double getArea()
{
double Area = width*length;
return Area;
}
public String toString()
{
return getClass().getName() + "[ width=" + width + "]"+ "[length=" + length + "]";
}
}
package shape;
public abstract class shape
{
double PI = 3.14;
public abstract double getPerimeter();
public abstract double getArea();
}
package shape;
public class Circle extends shape
{
private double radius;
public Circle(double r)
{
radius = r;
}
public double getPerimeter()
{
double Perimeter = 2*PI*radius;
return Perimeter;
}
public double getArea()
{
double Area = PI*radius*radius;
return Area;
}
public String toString()
{
return getClass().getName() + "[radius=" + radius + "]";
}
}
实验结果:
实验 3:编程练习 2
编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。
package qq;
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;
public class Test{
private static ArrayList<Citizen> citizenlist;
public static void main(String[] args) {
citizenlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("D:\\身份证号.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 address =linescanner.nextLine();
Citizen citizen = new Citizen();
citizen.setName(name);
citizen.setId(id);
citizen.setSex(sex);
citizen.setAge(age);
citizen.setAddress(address);
citizenlist.add(citizen);
}
} catch (FileNotFoundException e) {
System.out.println("信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("信息文件读取错误");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("1.按姓名查询");
System.out.println("2.按身份证号查询");
System.out.println("3.退出");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
System.out.println("请输入姓名");
String citizenname = scanner.next();
int nameint = findCitizenByname(citizenname);
if (nameint != -1) {
System.out.println("查找信息为:身份证号:"
+ citizenlist.get(nameint).getId() + " 姓名:"
+ citizenlist.get(nameint).getName() +" 性别:"
+citizenlist.get(nameint).getSex() +" 年龄:"
+citizenlist.get(nameint).getAge()+" 地址:"
+citizenlist.get(nameint).getAddress()
);
} else {
System.out.println("不存在该公民");
}
break;
case 2:
System.out.println("请输入身份证号");
String citizenid = scanner.next();
int idint = findCitizenByid(citizenid);
if (idint != -1) {
System.out.println("查找信息为:身份证号:"
+ citizenlist.get(idint ).getId() + " 姓名:"
+ citizenlist.get(idint ).getName() +" 性别:"
+citizenlist.get(idint ).getSex() +" 年龄:"
+citizenlist.get(idint ).getAge()+" 地址:"
+citizenlist.get(idint ).getAddress()
);
} else {
System.out.println("不存在该公民");
}
break;
case 3:
isTrue = false;
System.out.println("程序已退出!");
break;
default:
System.out.println("输入有误");
}
}
}
public static int findCitizenByname(String name) {
int flag = -1;
int a[];
for (int i = 0; i < citizenlist.size(); i++) {
if (citizenlist.get(i).getName().equals(name)) {
flag= i;
}
}
return flag;
}
public static int findCitizenByid(String id) {
int flag = -1;
for (int i = 0; i < citizenlist.size(); i++) {
if (citizenlist.get(i).getId().equals(id)) {
flag = i;
}
}
return flag;
}
}
package qq;
public class Citizen {
private String name;
private String id ;
private String sex ;
private String age;
private String address;
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 String getAge() {
return age;
}
public void setAge(String age ) {
this.age=age ;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address=address ;
}
}
实验结果:
实验总结:
上周我们学习了第五章,这章中主要学了继承这一概念,通过继承人们可以在已存在的类构造一个新类,继承已存在的类就是复用这些类的方法和域,通过继承这一概念我们学习了一些类的概念如:超类,基类(父类),子类等。总的来说本章的知识点也是比较重要的,不过我对本章的知识掌握的不是很好,我会继续努力的,多多敲代码。
201771010106 东文财《面向对象程序设计(java)》 实验 8
实验六 接口的定义与使用
实验时间 2018-10-18
一、理论知识部分
抽象类:
用 abstract 来声明,没有具体实例对象的类,不能用 new 来创建对象。可包含常规类所包含的任何东西。抽象类必须由子类继承,如果 abstract 类的子类不是抽象类,那么子类必须重写父类中所有的 abstract 方法。
接口:
用 interface 声明,是抽象方法和常量值定义的集合。从本质上讲,接口是一种特殊的抽象类,这种抽象类中只包含常量和方法的定义,而没有变量和方法的定义。接口中只能定义抽象方法,而且这些方法默认为是 public 的。只要类实现了接口,就可以在任何需要该接 口的地方使用这个类的对象。此外,一个类可以实现多个接口。
接口与抽象类的区别:
(1)接口不能实现任何方法,而抽象类可以。
(2)类可以实现许多接口,但只有一个父类。
(3)接口不是类分级结构的一部分,无任何联系的类可以实现相同的接口。
回调 (callback):
一种程序设计模式,在这种模式中,可指出某个特定事件发生时程序应该采取的动作。当拷贝一个对象变量时,原始变量与拷贝变量引用同一个对象。这样,改变一个变量所引用 的对象会对另一个变量产生影响。如果要创建一个对象新的 copy,它的最初状态与 original 一样,但以后可以各自改变状态,就需要使用 Object 类的 clone 方法。Object 类的 clone () 方法是一个 native 方法。Object 类中的 clone () 方法被 protected 修饰符修饰。这意味着在用户编写的代码中不能直接调用它。如果要直接应用 clone () 方法,就需覆盖 clone () 方法,并要把 clone () 方法的属性设置为 public。 Object.clone () 方法返回一个 Object 对象。必须进行强制类型转换才能得到需要的类型。
浅层拷贝:
被拷贝对象的所有常量成员和基本类型属性都有与原来对象相同的拷贝值,而若成员域是一个对象,则被拷贝对象该对象域的对象引用仍然指向原来的对象。
深层拷贝:
被拷贝对象的所有成员域都含有与原来对象相同的值,且对象域将指向被复制过的新对象,而不是原有对象被引用的对象。换言之, 深层拷贝将拷贝对象内引用的对象也拷贝一遍 。
Java 中对象克隆的实现:
在子类中实现 Cloneable 接口。为了获取对象的一份拷贝,可以利用 Object 类的 clone 方法。在子类中覆盖超类的 clone 方法,声明为 public。在子类的 clone 方法中,调用 super.clone ()。
二、实验部分
1、实验目的与要求
(1) 掌握接口定义方法;
(2) 掌握实现接口类的定义要求;
(3) 掌握实现了接口类的使用要求;
(4) 掌握程序回调设计模式;
(5) 掌握 Comparator 接口用法;
(6) 掌握对象浅层拷贝与深层拷贝方法;
(7) 掌握 Lambda 表达式语法;
(8) 了解内部类的用途及语法要求。
2、实验内容和步骤
实验 1: 导入第 6 章示例程序,测试程序并进行代码注释。
测试程序 1:
l 编辑、编译、调试运行阅读教材 214 页 - 215 页程序 6-1、6-2,理解程序并分析程序运行结果;
l 在程序中相关代码处添加新知识的注释。
l 掌握接口的实现用法;
l 掌握内置接口 Compareable 的用法。
package interfaces;
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)
{
return Double.compare(salary, other.salary);
}
}
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)
{
Employee[] 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);
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}
实验结果:
测试程序 2:
l 编辑、编译、调试以下程序,结合程序运行结果理解程序;
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); } } |
package gh;
public class yy {
// TODO Auto-generated method stub
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:
l 在 elipse IDE 中调试运行教材 223 页 6-3,结合程序运行结果理解程序;
l 26 行、36 行代码参阅 224 页,详细内容涉及教材 12 章。
l 在程序中相关代码处添加新知识的注释。
l 掌握回调程序设计模式;
package timer;
/**
@version 1.01 2015-05-12
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
// to resolve conflict with java.util.Timer
public class TimerTest
{
public static void main(String[] args)
{
ActionListener listener = new TimePrinter();
// construct a timer that calls the listener
// once every 10 seconds
Timer t = new Timer(10000, listener);
t.start();
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is " + new Date());
Toolkit.getDefaultToolkit().beep();
}
}
测试程序 4:
l 调试运行教材 229 页 - 231 页程序 6-4、6-5,结合程序运行结果理解程序;
l 在程序中相关代码处添加新知识的注释。
l 掌握对象克隆实现技术;
l 掌握浅拷贝和深拷贝的差别。
package clone;
/**
* This program demonstrates cloning.
* @version 1.10 2002-07-01
* @author Cay Horstmann
*/
public class CloneTest
{
public static void main(String[] args)
{
try
{
Employee original = new Employee("John Q. Public", 50000);
original.setHireDay(2000, 1, 1);
Employee copy = original.clone();
copy.raiseSalary(10);
copy.setHireDay(2002, 12, 31);
System.out.println("original=" + original);
System.out.println("copy=" + copy);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
package clone;
import java.util.Date;
import java.util.GregorianCalendar;
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();
}
public Employee clone() throws CloneNotSupportedException
{
// call Object.clone()
Employee cloned = (Employee) 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 表达式用法。
l 调试运行教材 233 页 - 234 页程序 6-6,结合程序运行结果理解程序;
l 在程序中相关代码处添加新知识的注释。
l 将 27-29 行代码与教材 223 页程序对比,将 27-29 行代码与此程序对比,体会 Lambda 表达式的优点。
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)
{
String[] 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);
System.out.println(Arrays.toString(planets));
System.out.println("Sorted by length:");
Arrays.sort(planets, (first, second) -> first.length() - second.length());
System.out.println(Arrays.toString(planets));
Timer t = new Timer(1000, event ->
System.out.println("The time is " + new Date()));
t.start();
// keep program running until user selects "Ok"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
实验结果:
注:以下实验课后完成
实验 3: 编程练习
l 编制一个程序,将身份证号.txt 中的信息读入到内存中;
l 按姓名字典序输出人员信息;
l 查询最大年龄的人员信息;
l 查询最小年龄人员信息;
l 输入你的年龄,查询身份证号.txt 中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;
l 查询人员中是否有你的同乡。
package yu;
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 yy{
private static ArrayList<People> Peoplelist;
public static void main(String[] args) {
Peoplelist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("D:\\java\\1\\身份证号.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 place =linescanner.nextLine();
People People = new people();
People.setname(name);
People.setID(ID);
People.setsex(sex);
int a = Integer.parseInt(age);
People.setage(a);
People.setbirthplace(place);
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:查询人员中是否有你的同乡");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
Collections.sort( Peoplelist);
System.out.println( Peoplelist.toString());
break;
case 2:
int max=0,min=100;int j,k1 = 0,k2=0;
for(int i=1;i< Peoplelist.size();i++)
{
j= Peoplelist.get(i).getage();
if(j>max)
{
max=j;
k1=i;
}
if(j<min)
{
min=j;
k2=i;
}
}
System.out.println("年龄最大:"+ Peoplelist.get(k1));
System.out.println("年龄最小:"+ Peoplelist.get(k2));
break;
case 3:
System.out.println("place?");
String find = scanner.next();
String place=find.substring(0,3);
String place2=find.substring(0,3);
for (int i = 0; i < Peoplelist.size(); i++)
{
if( Peoplelist.get(i).getbirthplace().substring(1,4).equals(place))
System.out.println(Peoplelist.get(i));
}
break;
case 4:
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near=agenear(yourage);
int d_value=yourage-Peoplelist.get(near).getage();
System.out.println(""+Peoplelist.get(near));
/* for (int i = 0; i < Peoplelist.size(); i++)
{
int p=Personlist.get(i).getage()-yourage;
if(p<0) p=-p;
if(p==d_value) System.out.println(Peoplelist.get(i));
} */
break;
case 5:
isTrue = false;
System.out.println("退出程序!");
break;
default:
System.out.println("输入有误");
}
}
}
public static int agenear(int age) {
int min=25,d_value=0,k=0;
for (int i = 0; i < Peoplelist.size(); i++)
{
d_value= Peoplelist.get(i).getage()-age;
if(d_value<0) d_value=-d_value;
if (d_value<min)
{
min=d_value;
k=i;
}
} return k;
}
}
package yu;
public class yu {
public abstract class People implements Comparable<People> {
private String name;
private String ID;
private int age;
private String sex;
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 int getage() {
return age;
}
public void setage(int age) {
// int a = Integer.parseInt(age);
this.age= age;
}
public String getsex() {
return sex;
}
public void setsex(String sex) {
this.sex= sex;
}
public String getbirthplace() {
return birthplace;
}
public void setbirthplace(String birthplace) {
this.birthplace= birthplace;
}
public int compareTo(People o) {
return this.name.compareTo(o.getname());
}
public String toString() {
return name+"\t"+sex+"\t"+age+"\t"+ID+"\t"+birthplace+"\n";
}
}
}
实验结果:
实验 4:内部类语法验证实验
实验程序 1:
l 编辑、调试运行教材 246 页 - 247 页程序 6-7,结合程序运行结果理解程序;
l 了解内部类的基本用法。
package innerClass;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
/**
* This program demonstrates the use of inner classes.
* @version 1.11 2015-05-12
* @author Cay Horstmann
*/
public class InnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock(1000, true);
clock.start();
// 在按确定之前,程序一直运行
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;
}
/**
* Starts the clock.
*/
public void start()
{
ActionListener listener = new TimePrinter();//构造器
Timer t = new Timer(interval, listener);
t.start();
}
public class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is " + new Date());
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
}
实验结果:
实验程序 2:
l 编辑、调试运行教材 254 页程序 6-8,结合程序运行结果理解程序;
l 了解匿名内部类的用法。
package anonymousInnerClass;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
/**
* This program demonstrates anonymous inner classes.
* @version 1.11 2015-05-12
* @author Cay Horstmann
*/
public class AnonymousInnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock();//TalkingClock类声明为私有的
clock.start(1000, true);
// keep program running until 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)
{
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is " + new Date());
if (beep) Toolkit.getDefaultToolkit().beep();
//外围类引用.
}
};
Timer t = new Timer(interval, listener);
t.start();
}
}
实验结果:
实验程序 3:
l 在 elipse IDE 中调试运行教材 257 页 - 258 页程序 6-9,结合程序运行结果理解程序;
l 了解静态内部类的用法。
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)
{
double[] d = new double[20];
for (int i = 0; i < d.length; i++)
d[i] = 100 * Math.random();
ArrayAlg.Pair p = ArrayAlg.minmax(d);
System.out.println("min = " + p.getFirst());
System.out.println("max = " + p.getSecond());
}
}
class ArrayAlg
{
/**
* A pair of floating-point numbers
*/
public static class 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()
{
return first;
}
/**
* Returns the second number of the pair
* @return the second number
*/
public double 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 表达式与内部类。也学会了建立浅拷贝与深拷贝,总的来说本章的知识点还是挺多的。以后我会继续努力,争取敲更多好的代码。
我们今天的关于201771010120 苏浪浪 《面向对象程序设计和java》第11周学习总结的分享已经告一段落,感谢您的关注,如果您想了解更多关于20172303 2017-2018-2 《程序设计与数据结构》第11周学习总结、20175221曾祥杰 第11周学习总结、201771010106 东文财《面向对象程序设计(java)》 实验 6、201771010106 东文财《面向对象程序设计(java)》 实验 8的相关信息,请在本站查询。
本文标签: