201771010126 王燕《面向对象程序设计(java)》第十一周学习总结
实验十一 集合
实验时间 2018-11-8
1、实验目的与要求
(1) 掌握Vetor、Stack、Hashtable三个类的用途及常用API;
Vector类实现了长度可变的数组。 Vector中只能存放对象。 Vector的元素通过下标进行访问。
Vector类关键属性:
capacity表示集合最多能容纳的元素个数。
capacityIncrement表示每次增加多少容量。
size表示集合当前元素个数。
Vector类的关键方法:
void addElement(Object obj)
void add(int index, Object element)
Object elementAt(int index)
void insertElementAt(Object obj, int index)
Stack类是Vector的子类。 Stack类描述堆栈数据结构,即LIFO。 Stack类的关键方法:
public void push(Object item):把项压入栈顶
public Object pop():移除栈顶对象并作为此函数的值返回该对象的值
public Object peek():查看栈顶对象但不移除
public boolean empty():测试堆栈是否为空
Hashtable通过键来查找元素。 Hashtable用一个特殊的值来确定键,名为hashcode(散列码)。所有对象都有一个散列码,可以通过Object 类的hashCode()方法获得。
(2) 了解java集合框架体系组成;
集合框架为程序员提供了一个功能强大的设计方案以解决编程过程中面临的大多数任务。下一次当你需要存储和检索信息时,可考虑使用类集。记住,类集不仅仅是专为那些“大型作业”,例如联合数据库,邮件列表或产品清单系统等所专用的。它们对于一些小型作业也是很有效的。例如,TreeMap可以给出一个很好的类集以保留一组文件的字典结构。TreeSet在存储工程管理信息时是十分有用的。坦白地说,对于采用基于类集的解决方案而受益的问题种类只受限于你的想象力。
(3) 掌握ArrayList、LinkList两个类的用途及常用API。
ArrayList内存中是顺序存储的。
LinkedList内存中是以链表方式存储的。
将线性表中的数据元素依次存放在某个存储区域中,所形成的表称为顺序表。一维数组就是用顺序方式存储的线性表。
ArrayList封装了一个动态再分配的对象数组,主要构造器和方法有:
public ArrayList()
public ArrayList(int initialCapacity)
public ArrayList(Collection<? extends E> elements)
public void trimToSize()
LinkedList<E>类的API:
public LinkedList()
public LinkedList(Collection<? extends E> elements)
public void addFirst(E element)
public void addLast(E element)
public E getFirst()
public E getLast()
public E removeFirst()
public E removeLast()
ArrayList底层采用数组完成,而LinkedList则是以一般的双向链表(double-linked list)完成,其内每个对象除了数据本身外,还有两个引用,分别指向前一个元素和后一个元素。 如果我们经常在List的开始处增加元素,或者在List中进行插入和删除操作,我们应该使用LinkedList,否则的话,使用ArrayList将更加快速。
(4) 了解HashSet类、TreeSet类的用途及常用API。
HashSet扩展AbstractSet并且实现Set接口。它创建一个使用散列表存储的集合。散列表(hash table)是通过使用称为散列法的机制来存储信息的。在散列法中,键的信息内容用于确定一个唯一的值,称为它的散列码。然后散列码作为与键相关的数据存储之处的索引使用。键到它的散列码的转化是自动完成的,我们不会看到散列码本身,同样,散列码也不能直接索引散列表。
散列集的构造方法: public HashSet() public HashSet(int initialCapacity) public HashSet(int initialCapacity,float loadFactor) public HashSet(Collection<? extends E> elements)
TreeSet类的底层结构为树的一种有序的Set。对象以升序顺序存储,访问和遍历它的时间很快,这使得TreeSet成为存储大量必须能很快查找的排序信息的很好选择。 TreeSet类的构造方法: public TreeSet() public TreeSet(Collection<? extends E> elements) public TreeSet(Comparator<? super E> elements) public TreeSet(SortedSet<E> elements) HashSet是基于Hash算法实现的,其性能通常都优于TreeSet。我们通常都应该使用HashSet,在我们需要排序的功能时,我们才使用TreeSet。
在默认情况下,树集假定插入的元素实现了Comparable接口。这个接口定义了一个方法: public interface Comparable<T> { int compareTo(T other); } 如果要插入自定义的对象,就必须通过实现Comparable接口自定义排序顺序。在Object类中,没有提供任何compareTo接口的默认实现。 class Item implements Comparable<Item> { public int compareTo(Item other){ …} }
由于使用Compareble接口定义排序的局限性(p367)。可以通过将Comparator对象传递给 TreeSort构造器来告诉树集使用不同的比较方法,从而允许在排序顺序上实现精确控制。 Comparator接口声明了一个带有两个显式参数的compare方法: public interface Comparator<T> { int compare(T a,T b); }
如果按照描述信息进行排序,就直接定义一个实现Comparator接口的类: Class ItemComparator implements Comparator<Item> { public int compare(Item a,Item b) { String descrA = a.getDescription(); String descrB = b.getDescription(); return descrA.compareTo(descrB); } } ItemComparator comp = new ItemComparator(); SortedSet<Item> sortByDescription = new TreeSet<>(comp);
(5)了解HashMap、TreeMap两个类的用途及常用API;
Map接口用来维持很多“键-值”对,以便通过键来查找相应的值。
HashMap基于散列表实现(替代Hashtable)。
HashMap是一个基于散列表完成的一个实现类,可以用它来取代Hashtable。 HashMap类的构造器: public HashMap() public HashMap(int initialCapacity) public HashMap(int initialCapacity, float loadFactor) public HashMap(Map<? extends K,? extends V> m)
TreeMap在一个二叉树的基础上实现。
TreeMap是底层基于树完成的一个Map。
当我们遍历它时,会以排序形式出现,次序由Comparable或Comparator比较器决定。 TreeMap类的构造器: public TreeMap() public TreeMap(Map<? extends K,? extends V> m) public TreeMap(Comparator<? super K> c) public TreeMap(SortedMap<K,? extends V> m)
(6) 结对编程(Pair programming)练习,体验程序开发中的两人合作。
2、实验内容和步骤
实验1: 导入第9章示例程序,测试程序并进行代码注释。
测试程序1:
l 使用JDK命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;
l 掌握Vetor、Stack、Hashtable三个类的用途及常用API。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.util.Vector; 2 3 class Cat { 4 private int catNumber; 5 6 Cat(int i) { 7 catNumber = i; 8 } 9 10 void print() { 11 System.out.println("Cat #" + catNumber); 12 } 13 } 14 15 class Dog { 16 private int dogNumber; 17 18 Dog(int i) { 19 dogNumber = i; 20 } 21 22 void print() { 23 System.out.println("Dog #" + dogNumber); 24 } 25 } 26 27 public class CatsAndDogs { 28 public static void main(String[] args) { 29 Vector cats = new Vector(); 30 for (int i = 0; i < 7; i++) 31 cats.addElement(new Cat(i)); 32 cats.addElement(new Dog(7)); 33 for (int i = 0; i < cats.size(); i++) { 34 if(cats.elementAt(i) instanceof Cat) 35 { 36 ((Cat) cats.elementAt(i)).print(); 37 } 38 else 39 { 40 ((Dog) cats.elementAt(i)).print();} 41 } 42 } 43 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.util.*; 2 3 public class Stacks { 4 static String[] months = { "1", "2", "3", "4" }; 5 6 public static void main(String[] args) { 7 Stack stk = new Stack(); 8 for (int i = 0; i < months.length; i++) 9 stk.push(months[i]); 10 System.out.println(stk); 11 System.out.println("element 2=" + stk.elementAt(2)); 12 while (!stk.empty()) 13 System.out.println(stk.pop()); 14 } 15 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.util.*; 2 3 class Counter { 4 int i = 1;//不加任何访问权限修饰符,缺省的是friendly 5 6 public String toString() { 7 return Integer.toString(i); 8 } 9 } 10 11 public class Statistics { 12 public static void main(String[] args) { 13 Hashtable ht = new Hashtable(); 14 for (int i = 0; i < 10000; i++) {//生成10000个随机的r(value)值,做循环 15 Integer r = new Integer((int) (Math.random() * 20));//在0~20以内随机生成一个整形数据(键值),Integer是整形包装器 16 if (ht.containsKey(r))//判断containsKey的键值 17 ((Counter) ht.get(r)).i++;//Counter类对象直接引用属性,get方法获得value值 18 else 19 ht.put(r, new Counter());//出现重复数据 20 } 21 System.out.println(ht); 22 } 23 }
//示例程序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"); } } |
l 在Elipse环境下编辑运行调试教材360页程序9-1,结合程序运行结果理解程序;
l 掌握ArrayList、LinkList两个类的用途及常用API。
1 import java.util.*; 2 3 /** 4 * This program demonstrates operations on linked lists. 5 * @version 1.11 2012-01-26 6 * @author Cay Horstmann 7 */ 8 public class LinkedListTest 9 { 10 public static void main(String[] args) 11 { 12 List<String> a = new LinkedList<>(); 13 a.add("Amy"); 14 a.add("Carl"); 15 a.add("Erica"); 16 17 List<String> b = new LinkedList<>(); 18 b.add("Bob"); 19 b.add("Doug"); 20 b.add("Frances"); 21 b.add("Gloria"); 22 23 // merge the words from b into a 24 25 ListIterator<String> aIter = a.listIterator(); 26 Iterator<String> bIter = b.iterator();//一开始迭代器(Iterator)在所有元素的左边,调用next()之后,迭代器移到第一个和第二个元素之间,next()方法返回迭代器刚刚经过的元素。 27 28 while (bIter.hasNext()) 29 { 30 if (aIter.hasNext()) aIter.next(); 31 aIter.add(bIter.next()); 32 } 33 34 System.out.println(a); 35 36 // remove every second word from b 37 38 bIter = b.iterator(); 39 while (bIter.hasNext()) 40 { 41 bIter.next(); // skip one element 42 if (bIter.hasNext()) 43 { 44 bIter.next(); // skip next element 45 bIter.remove(); // remove that element 46 } 47 } 48 49 System.out.println(b); 50 51 // bulk operation: remove all words in b from a 52 53 a.removeAll(b); 54 55 System.out.println(a); 56 } 57 }
测试程序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。
l 在Elipse环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API。
1 package Set; 2 3 import java.util.*; 4 5 /** 6 * This program uses a set to print all unique words in System.in. 7 * @version 1.12 2015-06-21 8 * @author Cay Horstmann 9 */ 10 public class SetTest 11 { 12 public static void main(String[] args) 13 { 14 Set<String> words = new HashSet<>(); // HashSet implements Set 15 long totalTime = 0; 16 17 try (Scanner in = new Scanner(System.in)) 18 { 19 while (in.hasNext()) 20 { 21 String word = in.next(); 22 long callTime = System.currentTimeMillis(); 23 words.add(word); 24 callTime = System.currentTimeMillis() - callTime; 25 totalTime += callTime; 26 } 27 } 28 29 Iterator<String> iter = words.iterator(); 30 for (int i = 1; i <= 20 && iter.hasNext(); i++) 31 System.out.println(iter.next()); 32 System.out.println(". . ."); 33 System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds."); 34 } 35 }
1 package treeSet; 2 3 import java.util.*; 4 5 /** 6 * An item with a description and a part number. 7 */ 8 public class Item implements Comparable<Item> 9 { 10 private String description; 11 private int partNumber; 12 13 /** 14 * Constructs an item. 15 * 16 * @param aDescription 17 * the item's description 18 * @param aPartNumber 19 * the item's part number 20 */ 21 public Item(String aDescription, int aPartNumber) 22 { 23 description = aDescription; 24 partNumber = aPartNumber; 25 } 26 27 /** 28 * Gets the description of this item. 29 * 30 * @return the description 31 */ 32 public String getDescription() 33 { 34 return description; 35 } 36 37 public String toString() 38 { 39 return "[description=" + description + ", partNumber=" + partNumber + "]"; 40 } 41 42 public boolean equals(Object otherObject) 43 { 44 if (this == otherObject) return true; 45 if (otherObject == null) return false; 46 if (getClass() != otherObject.getClass()) return false; 47 Item other = (Item) otherObject; 48 return Objects.equals(description, other.description) && partNumber == other.partNumber; 49 } 50 51 public int hashCode() 52 { 53 return Objects.hash(description, partNumber); 54 } 55 56 public int compareTo(Item other) 57 { 58 int diff = Integer.compare(partNumber, other.partNumber); 59 return diff != 0 ? diff : description.compareTo(other.description); 60 } 61 }
1 package treeSet; 2 3 import java.util.*; 4 5 /** 6 * This program sorts a set of item by comparing their descriptions. 7 * @version 1.12 2015-06-21 8 * @author Cay Horstmann 9 */ 10 public class TreeSetTest 11 { 12 public static void main(String[] args) 13 { 14 SortedSet<Item> parts = new TreeSet<>(); 15 parts.add(new Item("Toaster", 1234)); 16 parts.add(new Item("Widget", 4562)); 17 parts.add(new Item("Modem", 9912)); 18 System.out.println(parts); 19 20 NavigableSet<Item> sortByDescription = new TreeSet<>( 21 Comparator.comparing(Item::getDescription)); 22 23 sortByDescription.addAll(parts); 24 System.out.println(sortByDescription); 25 } 26 }
测试程序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); } } |
l 在Elipse环境下调试教材373页程序9-6,结合程序运行结果理解程序;
l 了解HashMap、TreeMap两个类的用途及常用API。
1 package map; 2 3 /** 4 * A minimalist employee class for testing purposes. 5 */ 6 public class Employee 7 { 8 private String name; 9 private double salary; 10 11 /** 12 * Constructs an employee with $0 salary. 13 * @param n the employee name 14 */ 15 public Employee(String name) 16 { 17 this.name = name; 18 salary = 0; 19 } 20 21 public String toString() 22 { 23 return "[name=" + name + ", salary=" + salary + "]"; 24 } 25 }
1 package map; 2 3 import java.util.*; 4 5 /** 6 * This program demonstrates the use of a map with key type String and value type Employee. 7 * @version 1.12 2015-06-21 8 * @author Cay Horstmann 9 */ 10 public class MapTest 11 { 12 public static void main(String[] args) 13 { 14 Map<String, Employee> staff = new HashMap<>(); 15 staff.put("144-25-5464", new Employee("Amy Lee")); 16 staff.put("567-24-2546", new Employee("Harry Hacker")); 17 staff.put("157-62-7935", new Employee("Gary Cooper")); 18 staff.put("456-62-5527", new Employee("Francesca Cruz")); 19 20 // print all entries 21 22 System.out.println(staff); 23 24 // remove an entry 25 26 staff.remove("567-24-2546"); 27 28 // replace an entry 29 30 staff.put("456-62-5527", new Employee("Francesca Miller")); 31 32 // look up a value 33 34 System.out.println(staff.get("157-62-7935")); 35 36 // iterate through all entries 37 38 staff.forEach((k, v) -> 39 System.out.println("key=" + k + ", value=" + v)); 40 } 41 }
实验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,结合使用体验对所运行程序提出完善建议;
1 package 小陈1; 2 import java.io.BufferedReader; 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.util.ArrayList; 9 import java.util.Arrays; 10 import java.util.Collections; 11 import java.util.Scanner; 12 public class Identity{ 13 private static ArrayList<Student> studentlist; 14 public static void main(String[] args) { 15 studentlist = new ArrayList<>(); 16 Scanner scanner = new Scanner(System.in); 17 File file = new File("G:\\JAVA\\实验\\身份证号.txt");//导入系统文件 18 try {//捕获文件读取异常以及导入异常 19 FileInputStream fis = new FileInputStream(file); 20 BufferedReader in = new BufferedReader(new InputStreamReader(fis)); 21 String temp = null; 22 while ((temp = in.readLine()) != null) { 23 24 Scanner linescanner = new Scanner(temp); 25 26 linescanner.useDelimiter(" "); 27 String name = linescanner.next(); 28 String number = linescanner.next(); 29 String sex = linescanner.next(); 30 String age = linescanner.next(); 31 String province =linescanner.nextLine(); 32 Student student = new Student(); 33 student.setName(name); 34 student.setnumber(number); 35 student.setsex(sex); 36 int a = Integer.parseInt(age); 37 student.setage(a); 38 student.setprovince(province); 39 studentlist.add(student); 40 } 41 } catch (FileNotFoundException e) { 42 System.out.println("学生信息文件找不到"); 43 e.printStackTrace(); 44 } catch (IOException e) { 45 System.out.println("学生信息文件读取错误"); 46 e.printStackTrace(); 47 } 48 boolean isTrue = true; 49 while (isTrue) { 50 System.out.println("选择你的操作,输入正确格式的选项"); 51 System.out.println("1.字典排序"); 52 System.out.println("2.输出年龄最大和年龄最小的人"); 53 System.out.println("3.寻找老乡"); 54 System.out.println("4.寻找年龄相近的人"); 55 System.out.println("0.退出"); 56 int status = scanner.nextInt(); 57 switch (status) { 58 case 1: 59 Collections.sort(studentlist); 60 System.out.println(studentlist.toString()); 61 break; 62 case 2: 63 int max=0,min=100; 64 int j,k1 = 0,k2=0; 65 for(int i=1;i<studentlist.size();i++) 66 { 67 j=studentlist.get(i).getage(); 68 if(j>max) 69 { 70 max=j; 71 k1=i; 72 } 73 if(j<min) 74 { 75 min=j; 76 k2=i; 77 } 78 79 } 80 System.out.println("年龄最大:"+studentlist.get(k1)); 81 System.out.println("年龄最小:"+studentlist.get(k2)); 82 break; 83 case 3: 84 System.out.println("老家?"); 85 String find = scanner.next(); 86 String place=find.substring(0,3); 87 for (int i = 0; i <studentlist.size(); i++) 88 { 89 if(studentlist.get(i).getprovince().substring(1,4).equals(place)) 90 System.out.println("老乡"+studentlist.get(i)); 91 } 92 break; 93 94 case 4: 95 System.out.println("年龄:"); 96 int yourage = scanner.nextInt(); 97 int near=agenear(yourage); 98 int value=yourage-studentlist.get(near).getage(); 99 System.out.println(""+studentlist.get(near)); 100 break; 101 102 case 0: 103 status = 0; 104 System.out.println("程序已退出!"); 105 break; 106 default: 107 System.out.println("输入错误"); 108 } 109 } 110 } 111 public static int agenear(int age) { 112 int min=53,value=0,k=0; 113 for (int i = 0; i < studentlist.size(); i++) 114 { 115 value=studentlist.get(i).getage()-age; 116 if(value<0) value=-value; 117 if (value<min) 118 { 119 min=value; 120 k=i; 121 } 122 } 123 return k; 124 } 125 126 }
1 package 小陈1; 2 3 public class Student implements Comparable<Student> { 4 private String name;//定义局部变量name,number,sex,age,province 5 private String number ; 6 private String sex ; 7 private int age; 8 private String province; 9 10 11 public String getName() {//定义构造方法 12 return name; 13 } 14 public void setName(String name) { 15 this.name = name; 16 } 17 public String getnumber() { 18 return number; 19 } 20 public void setnumber(String number) { 21 this.number = number; 22 } 23 public String getsex() { 24 return sex ; 25 } 26 public void setsex(String sex ) { 27 this.sex =sex ; 28 } 29 public int getage() { 30 return age; 31 } 32 public void setage(int age ) { 33 this.age=age ; 34 } 35 public String getprovince() { 36 return province; 37 } 38 public void setprovince(String province) { 39 this.province=province ; 40 } 41 @Override 42 public int compareTo(Student other) { 43 // TODO Auto-generated method stub 44 return this.name.compareTo(other.getName()); 45 } 46 47 public String toString() { 48 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; 49 } 50 }
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
1 package 小陈1; 2 3 import java.io.FileNotFoundException; 4 import java.io.PrintWriter; 5 import java.util.Scanner; 6 7 8 public class yunsuan { 9 public static void main(String[] args) { 10 11 Scanner in = new Scanner(System.in); 12 Pair student=new Pair(); 13 PrintWriter out = null; 14 try {//捕获异常 15 out = new PrintWriter("text.txt");//讲程序所出题目以及用户作答用文档形式保存在txt文档中 16 } catch (FileNotFoundException e) { 17 e.printStackTrace(); 18 } 19 int sum = 0; 20 21 22 23 for (int i = 1; i <=10; i++) { 24 int a = (int) Math.round(Math.random() * 100);//随机生成一个一百以内的数字 25 int b = (int) Math.round(Math.random() * 100);//随机生成一个一百以内的数字 26 int c= (int) Math.round(Math.random() * 3);//随机生成一个三以内的数字,并为随机产生的数字匹配相应的运算类型 27 28 29 switch(c)//使用switch语句做四则运算 30 { 31 case 0: 32 System.out.println(i+": "+a+"/"+b+"="); 33 34 while(b==0) 35 { 36 b = (int) Math.round(Math.random() * 100); 37 } 38 39 int C = in.nextInt(); 40 out.println(a+"/"+b+"="+C); 41 if (C == student.division(a, b)) { 42 sum += 10; 43 System.out.println("right"); 44 } 45 else { 46 System.out.println("false"); 47 } 48 49 break; 50 51 case 1: 52 System.out.println(i+": "+a+"*"+b+"="); 53 int D = in.nextInt(); 54 out.println(a+"*"+b+"="+D); 55 if (D == student.multiply(a, b)) { 56 sum += 10; 57 System.out.println("right"); 58 } 59 else { 60 System.out.println("false"); 61 } 62 break; 63 case 2: 64 System.out.println(i+": "+a+"+"+b+"="); 65 int E = in.nextInt(); 66 out.println(a+"+"+b+"="+E); 67 if (E == student.plus(a, b)) { 68 sum += 10; 69 System.out.println("right"); 70 } 71 else { 72 System.out.println("false"); 73 } 74 75 break ; 76 case 3: 77 System.out.println(i+": "+a+"-"+b+"="); 78 int F = in.nextInt(); 79 out.println(a+"-"+b+"="+F); 80 if (F == student.minus(a, b)) { 81 sum += 10; 82 System.out.println("right"); 83 } 84 else { 85 System.out.println("false"); 86 } 87 break ; 88 } 89 }//生成四则运算题目,并判断回答是否正确 90 System.out.println("成绩"+sum); 91 out.println("成绩:"+sum); 92 out.close(); 93 } 94 }
1 package 小陈1; 2 3 public class Pair<T> { 4 private T a;//创建局部变量a和b 5 private T b; 6 public Pair() 7 { 8 a = null; 9 b = null; 10 } 11 public Pair(T a,T b) 12 { 13 this.a = a; 14 this.b = b; 15 } 16 public T getA() 17 { 18 return a; 19 } 20 public T getB() 21 { 22 return b; 23 } 24 public int plus(int a,int b)//加法运算的构造方法 25 { 26 return a+b; 27 } 28 public int minus(int a,int b)//减法运算的构造方法 29 { 30 return a-b; 31 } 32 public int multiply(int a,int b)//乘法运算的构造方法 33 { 34 return a*b; 35 } 36 public int division(int a,int b)//除法法运算的构造方法 37 { 38 if(b!=0 && a%b==0) 39 return a/b; 40 else 41 return 0; 42 } 43 44 }
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
1 package 看到谁; 2 import java.io.FileNotFoundException; 3 import java.io.PrintWriter; 4 import java.util.Scanner; 5 public class Caculator { 6 public static void main(String[] args) { 7 Scanner in = new Scanner(System.in); 8 Caculator1 computing=new Caculator1(); 9 PrintWriter output = null; 10 //使用了异常处理机制,增强代码的安全性 11 try { 12 output = new PrintWriter("Caculator.txt"); 13 } catch (Exception e) { 14 } 15 int sum = 0; 16 //随机数生成,提供后续题目所用的数据 17 for (int i = 1; i < 11; i++) { 18 int a = (int) Math.round(Math.random() * 100); 19 int b = (int) Math.round(Math.random() * 100); 20 int s = (int) Math.round(Math.random() * 3); 21 //选择所要进行的操作 22 switch(s)//s为随机数,可随机执行下面四种操作 23 { 24 case 1: 25 System.out.println(i+": "+a+"/"+b+"="); 26 while(b==0){ 27 b = (int) Math.round(Math.random() * 100); 28 } 29 double c = in.nextDouble(); 30 output.println(a+"/"+b+"="+c); 31 //修改建议:生成除法题目时,对a,b两个数进行条件判断,确保整除,还有除数不为0 32 if (c == (double)computing.division(a, b)) { 33 sum += 10; 34 System.out.println("T"); 35 } 36 else { 37 System.out.println("F"); 38 } 39 40 break; 41 // 42 case 2: 43 System.out.println(i+": "+a+"*"+b+"="); 44 int c1 = in.nextInt(); 45 output.println(a+"*"+b+"="+c1); 46 if (c1 == computing.multiplication(a, b)) { 47 sum += 10; 48 System.out.println("T"); 49 } 50 else { 51 System.out.println("F"); 52 } 53 break; 54 case 3: 55 System.out.println(i+": "+a+"+"+b+"="); 56 int c2 = in.nextInt(); 57 output.println(a+"+"+b+"="+c2); 58 if (c2 == computing.addition(a, b)) { 59 sum += 10; 60 System.out.println("T"); 61 } 62 else { 63 System.out.println("F"); 64 } 65 66 break ; 67 case 4: 68 System.out.println(i+": "+a+"-"+b+"="); 69 int c3 = in.nextInt(); 70 output.println(a+"-"+b+"="+c3); 71 if (c3 == computing.subtraction(a, b)) { 72 sum += 10; 73 System.out.println("T"); 74 } 75 else { 76 System.out.println("F"); 77 } 78 break ; 79 80 } 81 82 } 83 System.out.println("scores:"+sum); 84 output.println("scores:"+sum); 85 output.close(); 86 87 } 88 } 89 class Caculator1 90 { 91 private int a; 92 private int b; 93 public int addition(int a,int b) 94 { 95 return a+b; 96 } 97 public int subtraction(int a,int b) 98 { 99 if((a-b)<0) 100 return 0; 101 else 102 return a-b; 103 } 104 public int multiplication(int a,int b) 105 { 106 return a*b; 107 } 108 public int division(int a,int b) 109 { 110 if(b!=0) 111 return a/b; 112 else 113 return 0; 114 } 115 116 117 } 118 119 四则运算
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习2。
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 import java.util.ArrayList; 8 import java.util.Arrays; 9 import java.util.Collections; 10 import java.util.Scanner; 11 public class Identity{ 12 private static ArrayList<Student> studentlist; 13 public static void main(String[] args) { 14 studentlist = new ArrayList<>(); 15 Scanner scanner = new Scanner(System.in); 16 File file = new File("C:/身份证号.txt"); 17 try { 18 FileInputStream fis = new FileInputStream(file); 19 BufferedReader in = new BufferedReader(new InputStreamReader(fis)); 20 String temp = null; 21 while ((temp = in.readLine()) != null) { 22 23 Scanner linescanner = new Scanner(temp); 24 25 linescanner.useDelimiter(" "); 26 String name = linescanner.next(); 27 String number = linescanner.next(); 28 String sex = linescanner.next(); 29 String age = linescanner.next(); 30 String province =linescanner.nextLine(); 31 Student student = new Student(); 32 student.setName(name); 33 student.setnumber(number); 34 student.setsex(sex); 35 int a = Integer.parseInt(age); 36 student.setage(a); 37 student.setprovince(province); 38 studentlist.add(student); 39 } 40 } catch (FileNotFoundException e) { 41 System.out.println("学生信息文件找不到"); 42 e.printStackTrace(); 43 } catch (IOException e) { 44 System.out.println("学生信息文件读取错误"); 45 e.printStackTrace(); 46 } 47 boolean isTrue = true; 48 while (isTrue) { 49 System.out.println("选择你的操作,输入正确格式的选项"); 50 System.out.println("1.字典排序"); 51 System.out.println("2.输出年龄最大和年龄最小的人"); 52 System.out.println("3.寻找老乡"); 53 System.out.println("4.寻找年龄相近的人"); 54 System.out.println("0.退出"); 55 int status = scanner.nextInt(); 56 switch (status) { 57 case 1: 58 Collections.sort(studentlist); 59 System.out.println(studentlist.toString()); 60 break; 61 case 2: 62 int max=0,min=100; 63 int j,k1 = 0,k2=0; 64 for(int i=1;i<studentlist.size();i++) 65 { 66 j=studentlist.get(i).getage(); 67 if(j>max) 68 { 69 max=j; 70 k1=i; 71 } 72 if(j<min) 73 { 74 min=j; 75 k2=i; 76 } 77 78 } 79 System.out.println("年龄最大:"+studentlist.get(k1)); 80 System.out.println("年龄最小:"+studentlist.get(k2)); 81 break; 82 case 3: 83 System.out.println("老家?"); 84 String find = scanner.next(); 85 String place=find.substring(0,3); 86 for (int i = 0; i <studentlist.size(); i++) 87 { 88 if(studentlist.get(i).getprovince().substring(1,4).equals(place)) 89 System.out.println("老乡"+studentlist.get(i)); 90 } 91 break; 92 93 case 4: 94 System.out.println("年龄:"); 95 int yourage = scanner.nextInt(); 96 int near=agenear(yourage); 97 int value=yourage-studentlist.get(near).getage(); 98 System.out.println(""+studentlist.get(near)); 99 break; 100 101 case 0: 102 status = 0; 103 System.out.println("程序已退出!"); 104 break; 105 default: 106 System.out.println("输入错误"); 107 } 108 } 109 } 110 public static int agenear(int age) { 111 int min=53,value=0,k=0; 112 for (int i = 0; i < studentlist.size(); i++) 113 { 114 value=studentlist.get(i).getage()-age; 115 if(value<0) value=-value; 116 if (value<min) 117 { 118 min=value; 119 k=i; 120 } 121 } 122 return k; 123 } 124 125 } 126 127 Identity
1 package 看到谁; 2 3 public class Student implements Comparable<Student> { 4 private String name; 5 private String number ; 6 private String sex ; 7 private int age; 8 private String province; 9 10 11 public String getName() { 12 return name; 13 } 14 public void setName(String name) { 15 this.name = name; 16 } 17 public String getnumber() { 18 return number; 19 } 20 public void setnumber(String number) { 21 this.number = number; 22 } 23 public String getsex() { 24 return sex ; 25 } 26 public void setsex(String sex ) { 27 this.sex =sex ; 28 } 29 public int getage() { 30 return age; 31 } 32 public void setage(int age ) { 33 this.age=age ; 34 } 35 public String getprovince() { 36 return province; 37 } 38 public void setprovince(String province) { 39 this.province=province ; 40 } 41 @Override 42 public int compareTo(Student other) { 43 // TODO Auto-generated method stub 44 return this.name.compareTo(other.getName()); 45 } 46 47 public String toString() { 48 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; 49 } 50 } 51 52 Student
实验总结:这一周结合上一周的血洗对于异常类的处理有了进一步的掌握,通过对之前实验的修改以及总结,还有同学间的合作扛到了很多自己的不足,和同学之间合作修改程序,对程序中自己觉察不到的bug再同学的建议下作了修改是的程序更加完整。