第十一周作业
本人学号:201771010138
姓名:邹丰蔚
《面向对象程序设计(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命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;
掌握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); } } |
得出结果:
测试程序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"); } } |
得出结果:
在Elipse环境下编辑运行调试教材360页程序9-1,结合程序运行结果理解程序;
掌握ArrayList、LinkList两个类的用途及常用API。
linkedList: package linkedList;
import java.util.*;
/** * This program demonstrates operations on linked lists. * @version 1.11 2012-01-26 * @author Cay Horstmann */ public class LinkedListTest { 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()); } } } |
得出结果:
在Elipse环境下调试教材365页程序9-2,结合运行结果理解程序;了解HashSet类的用途及常用API。
set: 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 implements 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."); } }
|
得出结果:
在Elipse环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API。
TreeSet: 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 { 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); } } Item: package treeSet;
import java.util.*;
/** * An item with a description and a part number. */ public class Item implements Comparable<Item> { private String description; private int partNumber;
/** * Constructs an item. * * @param aDescription * the item's description * @param aPartNumber * the item's part number */ public Item(String aDescription, int aPartNumber) { description = aDescription; partNumber = aPartNumber; }
/** * Gets the description of this item. * * @return the description */ public String getDescription() { return description; }
public String toString() { return "[description=" + description + ", partNumber=" + partNumber + "]"; }
public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Item other = (Item) otherObject; return Objects.equals(description, other.description) && partNumber == other.partNumber; }
public int hashCode() { return Objects.hash(description, partNumber); }
public int compareTo(Item other) { int diff = Integer.compare(partNumber, other.partNumber); return diff != 0 ? diff : description.compareTo(other.description); } } |
得出结果:
测试程序4:
使用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); } } |
得出结果:
l 在Elipse环境下调试教材程序9-5,9-6,结合程序运行结果理解程序;
l 了解HashMap、TreeMap两个类的用途及常用API。
PriorityQueue: package priorityQueue;
import java.util.*; import java.time.*;
/** * This program demonstrates the use of a priority queue. * @version 1.02 2015-06-20 * @author Cay Horstmann */ public class PriorityQueueTest { public static void main(String[] args) { PriorityQueue<LocalDate> pq = new PriorityQueue<>(); pq.add(LocalDate.of(1906, 12, 9)); // G. Hopper pq.add(LocalDate.of(1815, 12, 10)); // A. Lovelace pq.add(LocalDate.of(1903, 12, 3)); // J. von Neumann pq.add(LocalDate.of(1910, 6, 22)); // K. Zuse
System.out.println("Iterating over elements..."); for (LocalDate date : pq) System.out.println(date); System.out.println("Removing elements..."); while (!pq.isEmpty()) System.out.println(pq.remove()); } }
|
得出结果:
Map: 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<>(); 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)); } } Employee: package map;
/** * A minimalist employee class for testing purposes. */ public class Employee { private String name; private double salary;
/** * Constructs an employee with $0 salary. * @param n the employee name */ public Employee(String name) { this.name = name; salary = 0; }
public String toString() { return "[name=" + name + ", salary=" + salary + "]"; } }
|
得出结果:
实验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 确定本次实验结对编程合作伙伴;
合作伙伴:张季跃
l 各自运行合作伙伴实验九编程练习1,结合使用体验对所运行程序提出完善建议;
Main 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; import java.util.Collections;
public class 实验 {
public static People findPeopleByname(String name) { People flag = null; for (People people : peoplelist) { if(people.getName().equals(name)) { flag = people; } } return flag;
}
public static People findPeopleByid(String id) { People flag = null; for (People people : peoplelist) { if(people.getnumber().equals(id)) { flag = people; } } return flag;
}
private static ArrayList<People> agenear(int yourage) { // TODO Auto-generated method stub int j=0,min=53,d_value=0,k = 0; ArrayList<People> plist = new ArrayList<People>(); for (int i = 0; i < peoplelist.size(); i++) { d_value = peoplelist.get(i).getage() > yourage ? peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ; k = d_value < min ? i : k; min = d_value < min ? d_value : min; } for(People people : peoplelist) { if(people.getage() == peoplelist.get(k).getage()) { plist.add(people); } } return plist; }
private static ArrayList<People> peoplelist;
public static void main(String[] args) { peoplelist = new ArrayList<People>(); Scanner scanner = new Scanner(System.in); File file = new File("C:\\Users\\张季跃\\Desktop\\身份证号.txt"); try { FileInputStream files = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(files)); String temp = null; while ((temp = in.readLine()) != null) {
String[] information = temp.split("[ ]+"); People people = new People(); people.setName(information[0]); people.setnumber(information[1]); int A = Integer.parseInt(information[3]); people.setage(A); people.setsex(information[2]); for(int j = 4; j<information.length;j++) { people.setplace(information[j]); } 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.查询身份证号.txt中年龄与输入年龄最近的人"); System.out.println(" 5.查询人员中是否有输入地址的同乡"); System.out.println(" 6.退出"); System.out.println("******************************************"); int nextInt = scanner.nextInt(); switch (nextInt) { case 1: Collections.sort(peoplelist); System.out.println(peoplelist.toString()); break; case 2: int max=0; int j,k1 = 0; for(int i=1;i<peoplelist.size();i++) { j = peoplelist.get(i).getage(); if(j>max) { max = j; k1 = i; }
} System.out.println("年龄最大:"+peoplelist.get(k1)); break; case 3: int min = 100; int j1,k2 = 0; for(int i=1;i<peoplelist.size();i++) { j1 = peoplelist.get(i).getage(); if(j1<min) { min = j1; k2 = i; }
} System.out.println("年龄最小:"+peoplelist.get(k2)); break; case 4: System.out.println("年龄:"); int input_age = scanner.nextInt(); ArrayList<People> plist = new ArrayList<People>(); plist = agenear(input_age); for(People people : plist) { System.out.println(people.toString()); } break; case 5: System.out.println("请输入省份"); String find = scanner.next(); for (int i = 0; i <peoplelist.size(); i++) { String [] place = peoplelist.get(i).getplace().split("\t"); for(String temp : place) { if(find.equals(temp)) { System.out.println(" "+peoplelist.get(i)); break; } }
} break; case 6: isTrue = false; System.out.println("再见!"); break; default: System.out.println("输入有误"); } } }
} People: public class People implements Comparable<People> {
private String name = null; private String number = null; private int age = 0; private String sex = null; private String place = null;
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 int getage() { return age; } public void setage(int age ) { this.age = age; } public String getsex() { return sex; } public void setsex(String sex ) { this.sex = sex; } public String getplace() { return place; } public void setplace(String place) { if(this.place == null) { this.place = place; }else { this.place = this.place+ "\t" +place; }
} public int compareTo(People o) { return this.name.compareTo(o.getName()); } public String toString() { return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+place+"\n"; } }
|
实验结果:
我和合作伙伴的代码差不多,只有一些微小的地方不同。
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
package 实验3-2; import java.util.Random; import java.util.Scanner; public class 实验3{ int sum; public static void main(String[] args) { 实验3 t=new 实验3(); System.out.println("考试开始"); t.sum=0; Random r=new Random(); for(int i=0;i<10;i++) { t.core(); } System.out.println("考试结束"); System.out.println("你的总分为"+t.sum); } private void core() { Random r=new Random(); int m,n; m=r.nextInt(11); n=m%4; switch(n) { case 0: int a ,b,c; a=r.nextInt(101); b=r.nextInt(101); System.out.println(a+"+"+"("+b+")"+"="); Scanner x=new Scanner(System.in); c=x.nextInt(); if(c!=a+b) System.out.println("计算失误"); else { System.out.println("计算正确"); sum=sum+10; } break; case 1: int h,g,f; h=r.nextInt(101); g=r.nextInt(101); System.out.println(h+"-"+"("+g+")"+"= "); Scanner u=new Scanner(System.in); f=u.nextInt(); if(f!=h-g) System.out.println("计算失误"); else { System.out.println("计算正确"); sum=sum+10; }
break; case 2: int q,w,e; q=r.nextInt(101); w=r.nextInt(101); System.out.println(q+"*"+"("+w+")"+"= "); Scanner y=new Scanner(System.in); e=y.nextInt(); if(e!=q*w) System.out.println("回答错误"); else { System.out.println("回答正确"); sum=sum+10; } break; case 3: double j,k,l; j=r.nextInt(101); k=r.nextInt(101); if(k==0) k++; System.out.println(j+"/"+"("+k+")"+"= "); Scanner z=new Scanner(System.in); l=z.nextDouble(); if(l!=(j/k)/1.00) System.out.println("回答错误"); else { System.out.println("回答正常"); sum=sum+10; } PrintStream out = System.out; break; } } } |
实验结果:
数据输出的地方有些问题。
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
package 实验3;
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; import java.util.Collections;
public class 实验 {
public static People findPeopleByname(String name) { People flag = null; for (People people : peoplelist) { if(people.getName().equals(name)) { flag = people; } } return flag;
}
public static People findPeopleByid(String id) { People flag = null; for (People people : peoplelist) { if(people.getnumber().equals(id)) { flag = people; } } return flag;
}
private static ArrayList<People> agenear(int yourage) { // TODO Auto-generated method stub int j=0,min=53,d_value=0,k = 0; ArrayList<People> plist = new ArrayList<People>(); for (int i = 0; i < peoplelist.size(); i++) { d_value = peoplelist.get(i).getage() > yourage ? peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ; k = d_value < min ? i : k; min = d_value < min ? d_value : min; } for(People people : peoplelist) { if(people.getage() == peoplelist.get(k).getage()) { plist.add(people); } } return plist; }
private static ArrayList<People> peoplelist;
public static void main(String[] args) { peoplelist = new ArrayList<People>(); Scanner scanner = new Scanner(System.in); File file = new File("C:\\Users\\张季跃\\Desktop\\身份证号.txt"); try { FileInputStream files = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(files)); String temp = null; while ((temp = in.readLine()) != null) {
String[] information = temp.split("[ ]+"); People people = new People(); people.setName(information[0]); people.setnumber(information[1]); int A = Integer.parseInt(information[3]); people.setage(A); people.setsex(information[2]); for(int j = 4; j<information.length;j++) { people.setplace(information[j]); } 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.查询身份证号.txt中年龄与输入年龄最近的人"); System.out.println(" 5.查询人员中是否有输入地址的同乡"); System.out.println(" 6.退出"); System.out.println("******************************************"); int nextInt = scanner.nextInt(); switch (nextInt) { case 1: Collections.sort(peoplelist); System.out.println(peoplelist.toString()); break; case 2: int max=0; int j,k1 = 0; for(int i=1;i<peoplelist.size();i++) { j = peoplelist.get(i).getage(); if(j>max) { max = j; k1 = i; }
} System.out.println("年龄最大:"+peoplelist.get(k1)); break; case 3: int min = 100; int j1,k2 = 0; for(int i=1;i<peoplelist.size();i++) { j1 = peoplelist.get(i).getage(); if(j1<min) { min = j1; k2 = i; }
} System.out.println("年龄最小:"+peoplelist.get(k2)); break; case 4: System.out.println("年龄:"); int input_age = scanner.nextInt(); ArrayList<People> plist = new ArrayList<People>(); plist = agenear(input_age); for(People people : plist) { System.out.println(people.toString()); } break; case 5: System.out.println("请输入省份"); String find = scanner.next(); for (int i = 0; i <peoplelist.size(); i++) { String [] place = peoplelist.get(i).getplace().split("\t"); for(String temp : place) { if(find.equals(temp)) { System.out.println(" "+peoplelist.get(i)); break; } }
} break; case 6: isTrue = false; System.out.println("再见!"); break; default: System.out.println("输入有误"); } } }
}
package 实验3;
public class People implements Comparable<People> {
private String name = null; private String number = null; private int age = 0; private String sex = null; private String place = null;
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 int getage() { return age; } public void setage(int age ) { this.age = age; } public String getsex() { return sex; } public void setsex(String sex ) { this.sex = sex; } public String getplace() { return place; } public void setplace(String place) { if(this.place == null) { this.place = place; }else { this.place = this.place+ "\t" +place; }
} public int compareTo(People o) { return this.name.compareTo(o.getName()); } public String toString() { return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+place+"\n"; } }
|
得出结果:
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习2。
package test; import java.util.Random; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.FileNotFoundException; import java.util.Scanner; public class Test{ int sum; public static void main(String[] args) throws FileNotFoundException 实验3 t= new 实验3(); PrintStream out = System.out; PrintStream ps = new PrintStream("C:\\Users\\张季跃\\Desktop\\第十周实验报告\\text.txt"); System.setOut(ps); System.out.println("kaishiks"); System.out.println("本次测试共十道题,每题十分,满分一百分"); t.sum=0; Random r=new Random(); for(int i=0;i<10;i++) { t.core(); } System.out.println("考试结束"); System.out.println("你的总分为"+t.sum); } private void core() { Random r=new Random(); int m,n; m=r.nextInt(11); n=m%4; switch(n) { case 0: int a ,b,c; a=r.nextInt(101); b=r.nextInt(101); System.out.println(a+"+"+"("+b+")"+"="); Scanner x=new Scanner(System.in); c=x.nextInt(); if(c!=a+b) System.out.println("回答错误"); else { System.out.println("回答正确"); sum=sum+10; } break; case 1: int h,g,f; h=r.nextInt(101); g=r.nextInt(101); System.out.println(h+"-"+"("+g+")"+"= "); Scanner u=new Scanner(System.in); f=u.nextInt(); if(f!=h-g) System.out.println("回答错误"); else { System.out.println("回答正确"); sum=sum+10; } break; case 2: int q,w,e; q=r.nextInt(101); w=r.nextInt(101); System.out.println(q+"*"+"("+w+")"+"= "); Scanner y=new Scanner(System.in); e=y.nextInt(); if(e!=q*w) System.out.println("回答错误"); else { System.out.println("回答正确"); sum=sum+10; } break; case 3: double j,k,l; j=r.nextInt(101); k=r.nextInt(101); if(k==0) k++; System.out.println(j+"/"+"("+k+")"+"= "); Scanner z=new Scanner(System.in); l=z.nextDouble(); if(l!=(j/k)/1.00) System.out.println("回答错误"); else { System.out.println("回答正常"); sum=sum+10; } break; } } } |
得出结果:
总结:通过这次实验,我了解了Vetor、Stack、Hashtable三个类的用途,ArrayList、LinkList两个类的用途,HashSet类的用途,TreeSet类的用途,HashMap、TreeMap两个类的用途。通过与合作伙伴的共同合作和学习,学到了很多东西,也充分认识到了自己的不足。