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。
import java.util.Vector; //示例程序1 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++) if(cats.elementAt(i)instanceof Cat)// instanceof运算符是用来指出对象是否是特定类的一个实例 { ((Cat) cats.elementAt(i)).print(); }else { ((Dog) 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;//不加权限修饰符:friendly型 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));//生成0到20(不包括20)的整型随机数 if (ht.containsKey(r))//判断r是否是哈希表中一个元素的键值 ((Counter) ht.get(r)).i++;//通过get方法获得其值 else ht.put(r, new Counter());//ht不存在 } System.out.println(ht); } }
测试程序2:
使用JDK命令编辑运行ArrayListDemo和LinkedListDemo两个程序,结合程序运行结果理解程序;
ArrayListDemo:
import java.util.*; public class ArrayListDemo//ArrayList使用了数组的实现 { public static void main(String[] argv) { ArrayList al = new ArrayList(); //在ArrayList中添加大量元素 al.add(new Integer(11)); al.add(new Integer(12)); al.add(new Integer(13)); al.add(new String("hello"));//下标从0开始,添加4个元素 // 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())//通过hasNext方法依次访问 System.out.println(li.next()); if (l.indexOf("Hello") < 0) //通过l调用indexOf方法 System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } }
l 在Elipse环境下编辑运行调试教材360页程序9-1,结合程序运行结果理解程序;
l 掌握ArrayList、LinkList两个类的用途及常用API。
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) { //创建a和b两个链表 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"); //合并a和b中的词 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); //从第二个链表中每隔一个元素删除一个元素 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);//通过AbstractCollection类中的toString方法打印出链表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环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API。
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); } }
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));//把自定义类对象存入TreeSet进行排序 sortByDescription.addAll(parts); System.out.println(sortByDescription); } }
测试程序4:
l 使用JDK命令运行HashMapDemo程序,结合程序运行结果理解程序;
程序如下:
import java.util.*; public class HashMapDemo //基于哈希表的 Map接口的实现,提供所有可选的映射操作 { public static void main(String[] argv) { HashMap h = new HashMap(); // 哈希映射从公司名称到地址 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,结合程序运行结果理解程序;
了解HashMap、TreeMap两个类的用途及常用API。
程序如下:
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//Map在有映射关系时,可以优先考虑 { 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")); // 打印所有条目 System.out.println(staff); // 删除一个条目 staff.remove("567-24-2546"); // 替换一个条目 staff.put("456-62-5527", new Employee("Francesca Miller")); // 查找一个值 System.out.println(staff.get("157-62-7935")); // 遍历所有条目 staff.forEach((k, v) -> System.out.println("key=" + k + ", value=" + v)); } }
实验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,结合使用体验对所运行程序提出完善建议;
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.List; import java.util.Scanner; public class Xinxi { 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"); 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) {//添加的异常处理语句try{ }catch{ }语句 System.out.println("所找信息文件找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("所找信息文件读取错误");//采取积极方法捕获异常,并将异常返回自己所设定的打印文字 e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("选择你的操作,输入正确格式的选项"); System.out.println("1按姓名字典序输出人员信息"); System.out.println("2.查询最大和最小年龄的人员信息"); System.out.println("3.寻找老乡"); System.out.println("4.寻找年龄相近的人的信息"); System.out.println("5.退出"); String n = scanner.next(); switch (n) { case "1": Collections.sort(studentlist); System.out.println(studentlist.toString()); break; case "2": int max = 0, min = 100; int j, k1 = 0, k2 = 0; for (int i = 1; i < studentlist.size(); i++) { j = studentlist.get(i).getage(); if (j > max) { max = j; k1 = i; } if (j < min) { min = j; k2 = i; } } System.out.println("年龄最大:" + studentlist.get(k1)); System.out.println("年龄最小:" + studentlist.get(k2)); break; case "3": System.out.println("家乡在哪里?"); String find = scanner.next(); String place = find.substring(0, 3); for (int i = 0; i < studentlist.size(); i++) { if (studentlist.get(i).getprovince().substring(1, 4).equals(place)) System.out.println("同乡" + studentlist.get(i)); } break; case "4": System.out.println("年龄:"); int yourage = scanner.nextInt(); int near = agenear(yourage); int value = yourage - studentlist.get(near).getage(); System.out.println("" + studentlist.get(near)); break; case "5": isTrue = false; System.out.println("退出程序!"); break; default: System.out.println("输入有误"); } } } public static int agenear(int age) { int j = 0, min = 53, value = 0, flag = 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; flag = i; } } return flag; } }
public class Student implements Comparable<Student> { private String name; private String number; private String sex; private String province; private int age; public void setName(String name) { // TODO 自动生成的方法存根 this.name = name; } public String getName() { // TODO 自动生成的方法存根 return name; } public void setnumber(String number) { // TODO 自动生成的方法存根 this.number = number; } public String getNumber() { // TODO 自动生成的方法存根 return number; } public void setsex(String sex) { // TODO 自动生成的方法存根 this.sex = sex; } public String getsex() { // TODO 自动生成的方法存根 return sex; } public void setprovince(String province) { // TODO 自动生成的方法存根 this.province = province; } public String getprovince() { // TODO 自动生成的方法存根 return province; } public void setage(int a) { // TODO 自动生成的方法存根 this.age = age; } public int getage() { // TODO 自动生成的方法存根 return age; } public int compareTo(Student o) { return this.name.compareTo(o.getName()); } public String toString() { return name + " " + sex + " " + age + " " + number + " " + province + " "; } }
package 第九周; import java.util.Random; import java.util.Scanner; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Demo { public static void main(String[] args) { // 用户的答案要从键盘输入,因此需要一个键盘输入流 Scanner in = new Scanner(System.in); yunsuan counter = new yunsuan (); PrintWriter out = null; try { out = new PrintWriter("D:\text.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int sum = 0; // 通过循环生成10道题 for (int i = 0; i < 10; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); //Scanner in1 =new Scanner(System.in); Random rand=new Random(); switch((int)(Math.random()*4)+1) { case 1: System.out.println( ""+a+"+"+b+"="); int c= in.nextInt(); out.println(a+"+"+b+"="+c); if (c == counter.add(a, b)) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉答案错误"); } break ; case 2: while (a<b) { b = (int)Math.round(Math.random() * 100); ; } System.out.println(i + ": " + a + "-" + b + "="); int c1 = in.nextInt(); out.println(a + "-" + b + "=" + c1); if (c1 == counter.reduce(a, b)) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉答案错误"); } break; case 3: System.out.println(i + ": " + a + "*" + b + "="); int c2 = in.nextInt(); out.println(a + "*" + b + "=" + c2); if (c2 == counter.multiplication(a, b)) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉答案错误"); } break; case 4: a = b + (int) Math.round(Math.random() * 100); while(b==0) { b = (int) Math.round(Math.random() * 100); } while (a%b==0) { a= (int) Math.round(Math.random() * 100); } System.out.println(""+a+"/"+b+"="); int c3= in.nextInt(); out.println(a+"/"+b+"="+c3); if (c3 == counter.devision(a, b)) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉答案错误"); } break; } } System.out.println("总分:"+sum); out.println(sum); out.close(); } }
package 第九周; public class yunsuan<T>{ private T a; private T b; public yunsuan() { a=null; b=null; } public int multiplication(int a, int b) { // TODO 自动生成的方法存根 return a*b; } public int add(int a, int b) { // TODO 自动生成的方法存根 return a+b; } public int reduce(int a, int b) { // TODO 自动生成的方法存根 if((a-b)>0)//保证两数相减不会是负数 return a-b; else return 0; } public int devision(int a, int b) { // TODO 自动生成的方法存根 if (b != 0 && a%b==0)//保证是整除 return a/b; else return 0; } }
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
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;//对集合进行排序、查找、修改等; 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("E:/java/身份证号.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); // 将字符串转换成10进制数 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(); } boolean isTrue = true; while (isTrue) { System.out.println("1.按姓名字典序输出人员信息"); System.out.println("2.查询最大年龄的人员信息、查询最小年龄人员信息"); System.out.println("3.查询人员中是否查询人员中是否有你的同乡"); System.out.println("4.输入你的年龄,查询文件中年龄与你最近人的姓名、身份证号、年龄、性别和出生地"); System.out.println("5.退出"); int nextInt = scanner.nextInt(); switch (nextInt) { case 1: Collections.sort(citizenlist); System.out.println(citizenlist.toString()); break; case 2: int max = 0, min = 100; int m, k1 = 0, k2 = 0; for (int i = 1; i < citizenlist.size(); i++) { m = citizenlist.get(i).getage(); if (m > max) { max = m; k1 = i; } if (m < min) { min = m; k2 = i; } } System.out.println("年龄最大:" + citizenlist.get(k1)); System.out.println("年龄最小:" + citizenlist.get(k2)); break; case 3: System.out.println("出生地:"); String find = scanner.next(); String place = find.substring(0, 3); for (int i = 0; i < citizenlist.size(); i++) { if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place)) System.out.println("出生地" + citizenlist.get(i)); } break; case 4: System.out.println("年龄:"); int yourage = scanner.nextInt(); int near = peer(yourage); int j = yourage - citizenlist.get(near).getage(); System.out.println("" + citizenlist.get(near)); break; case 5: isTrue = false; System.out.println("程序已退出!"); break; default: System.out.println("输入有误"); } } } public static int peer(int age) { int flag = 0; int min = 53, j = 0; for (int i = 0; i < citizenlist.size(); i++) { j = citizenlist.get(i).getage() - age; if (j < 0) j = -j; if (j < min) { min = j; flag = i; } } return flag; } }
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 + " " + sex + " " + age + " " + id + " " + birthplace + " "; } }
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习2。
import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class calculator { public static void main(String[] args) { Scanner in = new Scanner(System.in); Count count=new Count(); PrintWriter out = null; try { out = new PrintWriter("test.txt"); int sum = 0; for (int i = 1; i <=10; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int menu = (int) Math.round(Math.random() * 3); switch (menu) { case 0: System.out.println(i+":"+a + "+" + b + "="); int c1 = in.nextInt(); out.println(a + "+" + b + "=" + c1); if (c1 == (a + b)) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉,答案错误"); } break; case 1: while (a < b) { b = (int) Math.round(Math.random() * 100); } System.out.println(i+":"+a + "-" + b + "="); int c2 = in.nextInt(); out.println(a + "-" + b + "=" + c2); if (c2 == (a - b)) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉,答案错误"); } break; case 2: System.out.println(i+":"+a + "*" + b + "="); int c3 = in.nextInt(); out.println(a + "*" + b + "=" + c3); if (c3 == a * b) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉,答案错误"); } break; case 3: while(b == 0){ b = (int) Math.round(Math.random() * 100); } while(a % b != 0){ a = (int) Math.round(Math.random() * 100); } System.out.println(i+":"+a + "/" + b + "="); int c4 = in.nextInt(); if (c4 == a / b) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉,答案错误"); } break; } } System.out.println("你的得分为" + sum); out.println("你的得分为" + sum); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
public class Count<T> { private T a; private T b; public Count() { a=null; b=null; } public Count(T a,T b) { this.a=a; this.b=b; } public int count1(int a,int b) { return a+b; } public int count2(int a,int b) { return a-b; } public int count3(int a,int b) { return a*b; } public int count4(int a,int b) { return a/b; } }
实验总结:
通过本周学习,我了解了集合框架,另外初步了解了java集合类,也了解了Vector类,Stack类以及Hashtable类。此次实验第一次采用结对编程的方法,通过和合作伙伴互相运行程序,相互讨论交流,从中学到了很多东西,也发现了很多不足。我们从伙伴对方学到东西,改正不足,继续努力。