实验十一 集合
实验时间 2018-11-8
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:
因为dog类无法强制类型转换为cat类,所以程序会出现以下错误:
更改思路(两种方法):
(1)输出cat类时,将dog类放到cat类的输出循环之外,并将Dog(7)中的内容强制转换成dog类后单独输出。
更改后代码:
package demo; 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 < 7; i++) ((Cat) cats.elementAt(i)).print(); ((Dog) cats.elementAt(7)).print(); } }
(2)输出结果时,使用instanceof语句对类(cat和dog类)进行判断,根据情况输出。
更改后代码:
package demo; 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++) if(cats.elementAt(i) instanceof Cat) { ((Cat) cats.elementAt(i)).print(); } else ((Dog) cats.elementAt(i)).print(); } }
更改后的结果(均为以下结果):
示例程序2:
示例程序3:
程序解析:
该示例检验Math.random()方法的随机性。在理想情况下,该方法应该产生一系列完美的随机分布的数字。为了验证这一点,需要生成数量众多的随机数字,然后计算落在不同范围内的数字量。该程序生成10000个随数,查看它们在0~20之间的分布如何。
package demo; import java.util.*; class Counter { int i = 1; //default:即不加任何访问修饰符,通常称为“默认访问模式“。该模式下,只允许在同一个包中进行访问。 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)); //用Math.random()方法生成0到19的所有整数,并以int型存放,同时用Integer方法封装到数组中 if (ht.containsKey(r)) ((Counter) ht.get(r)).i++; else ht.put(r, new Counter()); //输出r中数据的键值对出现的次数 } System.out.println(ht); } }
运行结果:
关于int i为何种访问权限修饰符的思考(上课所提到的):
测试程序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。
ArrayListDemo(运行结果):
增加System.out.println(al.size());语句可以输出有多少个元素
LinkedListDemo(运行结果):
教材p360 9-1程序:
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<>(); //生成一个String型数组a,用add方法追加元素 a.add("Amy"); a.add("Carl"); a.add("Erica"); List<String> b = new LinkedList<>(); //生成一个String型数组b,用add方法追加元素 b.add("Bob"); b.add("Doug"); b.add("Frances"); b.add("Gloria"); // merge the words from b into a //将b数组中的单词合并到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 //删除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中删除b中的所有单词 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 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."); } }
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 { 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); } }
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:
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,结合程序运行结果理解程序;
了解HashMap、TreeMap两个类的用途及常用API。
代码:
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)); } }
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,结合使用体验对所运行程序提出完善建议;
王斌龙的代码:
package ba; 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 Cardtest { // 文件读取模块 利用ArrayList构造studentlist存放文件内容 private static ArrayList<Card> cardlist; public static void main(String[] args) { cardlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("C:\身份证号.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 area = linescanner.nextLine(); Card card = new Card(); card.setName(name); card.setId(id); card.setSex(sex); int a = Integer.parseInt(age); card.setAge(a); card.setArea(area); cardlist.add(card); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("信息文件找不到"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("信息文件读取错误"); e.printStackTrace(); } // 根据实验要求,利用switch语句选不同操作的模块 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.退出"); int nextInt = scanner.nextInt(); switch (nextInt) { case 1: Collections.sort(cardlist); System.out.println(cardlist.toString()); break; case 2: int max = 0, min = 100; int j, k1 = 0, k2 = 0; for (int i = 1; i < cardlist.size(); i++) { j = cardlist.get(i).getAge(); if (j > max) { max = j; k1 = i; } if (j < min) { min = j; k2 = i; } } System.out.println("年龄最大:" + cardlist.get(k1)); System.out.println("年龄最小:" + cardlist.get(k2)); break; case 3: System.out.println("你的年龄:"); int yourage = scanner.nextInt(); int near = agenear(yourage); System.out.println(cardlist.get(near)); break; case 4: System.out.println("你的家乡?"); String find = scanner.next(); String place = find.substring(0, 3); for (int i = 0; i < cardlist.size(); i++) { if (cardlist.get(i).getArea().substring(1, 4).equals(place)) System.out.println("老乡 " + cardlist.get(i)); } break; case 5: isTrue = false; System.out.println("程序已退出!"); break; default: System.out.println("输入有误"); } } } //寻找年龄相近的人的位置 public static int agenear(int age) { int j = 0, min = 100, value = 0, k = 0; for (int i = 0; i < cardlist.size(); i++) { value = cardlist.get(i).getAge() - age; if (value < 0) value = -value; if (value < min) { min = value; k = i; } } return k; } }
package ba; //对数据具体处理的模块 public class Card implements Comparable<Card> { private String name; private String id; private String sex; private int age; private String area; //返回具体的数据 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 getArea() { return area; } public void setArea(String area) { this.area = area; } // 按名字的字典顺序排列 public int compareTo(Card c) { return this.name.compareTo(c.getName()); } // 用toString方法返回数据 public String toString() { return name + " " + id + " " + sex + " " + age + " " + area + " "; } } Card
完善建议:
简化代码的行数
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
王斌龙的代码:
package 异常; import java.io.PrintWriter; import java.util.Scanner; public class Test { public static void main(String[] args) { @SuppressWarnings("resource") Scanner in = new Scanner(System.in); Demo demo=new Demo(); PrintWriter output = null; try { output = new PrintWriter("test.txt"); } catch (Exception e) { 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 c = (int) Math.round(Math.random() * 3); switch (c) { case 0: System.out.println(a + "+" + b + "="); int d0 = in.nextInt(); output.println(a + "+" + b + "=" + d0); if (d0 == demo.demo1(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(); output.println(a + "-" + b + "=" + d1); if (d1 == demo.demo2(a, b)) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉,答案错误"); } break; case 2: System.out.println(a + "*" + b + "="); int d2 = in.nextInt(); output.println(a + "*" + b + "=" + d2); if (d2 == demo.demo3(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(); output.println(a + "/" + b + "=" + d3); if (d3 == demo.demo4(a, b)) { sum += 10; System.out.println("恭喜答案正确"); } else { System.out.println("抱歉,答案错误"); } break; } } System.out.println("你的得分为" + sum); output.println("你的得分为" + sum); output.close(); } }
package 异常; public class Demo<T> { private T a; private T b; public Demo() { a = null; b = null; } public Demo(T a, T b) { this.a = a; this.b = b; } public int demo1(int a, int b) { return a + b; } public int demo2(int a, int b) { return a - b; } public int demo3(int a, int b) { return a * b; } public int demo4(int a, int b) { return a / b; } }
完善建议:
个人认为,为了程序的严谨性,需要在Demo类中的除法计算语句(模块)中加入“a>b,a%b==0,(a/b)%1==0”的限制条件(语句)
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
package shen; 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 { /** * 1.文件读取模块 利用ArrayList构造studentlist存放文件内容2. 创建文件字符流,分类读取文件内容 3.try/catch语句捕获异常 */ private static ArrayList<Student> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("C:\Users\ASUS\Desktop\新建文件夹\身份证号.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(); // 加入的捕获异常代码 } /* * 1.根据实验要求,选择具体操作的模块 2.利用switch语句选择具体的操作 */ 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("F.退出"); 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 "F": 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 shen; /* * 分类返回具体数据 *利用接口技术比较name的大小 *用toString方法返回数据 */ 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 + " " + sex + " " + age + " " + number + " " + province + " "; } }
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习2。
package demo; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class demo { public static void main(String[] args) { /** *文件输出模块 *1.调用构造函数counter *2.创建文件字符流,将out中的内容设为空(null) *3.将out结果输出到test.txt中 *4.try/catch模块捕获异常 */ Scanner in = new Scanner(System.in); yunsuan counter = new yunsuan(); PrintWriter out = null; try { out = new PrintWriter("text.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } /** *四则运算生成模块 *1.定义一个int型sum,计算成绩,并说明生成的运算类型 *2.for语句,将{}内的内容循环10次,从而生成10道题目 *3.随机生成int型a与b,范围在0到100以内;生成int型m,范围为1,2,3,4 *4.利用switch语句,根据生成m的值,随机生成加减乘除四则运算 *5.将循环结果输出到test.txt中 */ int sum = 0; System.out.println("随机生成的四则运算类型"); System.out.println("类型1:除法"); System.out.println("类型2:乘法"); System.out.println("类型3:加法"); System.out.println("类型4:减法"); for (int i = 1; i <= 10; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int m; Random rand = new Random(); m = (int) rand.nextInt(4) + 1; System.out.println("随机生成的四则运算类型:"+m); switch (m) { case 1: System.out.println(i + ": " + a + "/" + b + "="); while (b == 0) { b = (int) Math.round(Math.random() * 100); } double c0 = in.nextDouble(); out.println(a + "/" + b + "=" + c0); if (c0 == counter.division(a, b)) { sum += 10; System.out.println("right!"); } else { System.out.println("error!"); } break; case 2: System.out.println(i + ": " + a + "*" + b + "="); int c = in.nextInt(); out.println(a + "*" + b + "=" + c); if (c == counter.multiplication(a, b)) { sum += 10; System.out.println("right!"); } else { System.out.println("error!"); } break; case 3: System.out.println(i + ": " + a + "+" + b + "="); int c1 = in.nextInt(); out.println(a + "+" + b + "=" + c1); if (c1 == counter.add(a, b)) { sum += 10; System.out.println("right!"); } else { System.out.println("error!"); } break; case 4: System.out.println(i + ": " + a + "-" + b + "="); int c2 = in.nextInt(); out.println(a + "-" + b + "=" + c2); if (c2 == counter.reduce(a, b)) { sum += 10; System.out.println("right!"); } else { System.out.println("error!"); } break; } } System.out.println("成绩" + sum); out.println("成绩:" + sum); out.close(); } }
package demo; public class yunsuan { private int a; private int b; public int add(int a,int b) { return a+b; } public int reduce(int a,int b) { return a-b; } public int multiplication(int a,int b) { return a*b; } public int division(int a,int b) { if(b!=0) return a/b; else return 0; } }
运行结果:
学习总结:
集合
1.数据结构介绍
l 般将数据结构分为两大类:线性数据结构和非线性数据结构。
l 线性数据结构:线性表、栈、队列、串、数组和文件。
l 非线性数据结构:树和图。
A.线性表
单向链表
循环链表
双向循环链表
B.栈(Stack)
C.队列(Queue)
D.散列表
2.JAVA的集合框架
l JAVA的集合框架实现对各种数据结构的封装,以降低对数据管理与处理的难度。
l 所谓框架就是一个类库的集合,框架中包含很多超类,编程者创建这些超类的子类可较方便的设计设计程序所需的类。例如:Swing类包
l 集合(Collection或称为容器)是一种包含多个元素并提供对所包含元素操作方法的类,其包含的元素可以由同一类型的对象组成,也可以由不同类型的对象组成。
l 集合框架:JAVA集合类库的统一架构。
1.集合类的作用
l 集合类的作用:
– Java的集合类提供了一些基本数据结构的支持。
– 例如Vector、Hashtable、Stack等。
l 集合类的使用:
– Java的集合类包含在java.util包中。
– import java.util.*;
2.集合类的特点
l 特点一:
– 只容纳对象。
注意:数组可以容纳基本数据类型数据和对象。
– 如果集合类中想使用基本数据类型,又想利用集合类的灵活性,可以把基本数据类型数据封装成该数据类型的包装器对象,然后放入集合中处理。
l 特点二:
– 集合类容纳的对象都是Object类的实例,一旦把一个对象置入集合类中,它的类信息将丢失,这样设计的目的是为了集合类的通用性。
– 因为Object类是所有类的祖先,所以可以在这些集合中存放任何类的对象而不受限制,但切记在使用集合成员之前必须对它重新造型。
3. 新旧集合类
Vector类
Stack类
Hashtable类
集合框架中的基本接口
l Collection:集合层次中的根接口,JDK未提供这个接口的直接实现类。
l Set:不能包含重复的元素。对象可能不是按存放的次序存放,也就是说不能像数组一样按索引的方式进行访问,SortedSet是一个按照升序排列元素的Set。
l List:是一个有序的集合,可以包含重复的元素。提供了按索引访问的方式。
l Map:包含了key-value对。Map不能包含重复的key。
l SortedMap是一个按照升序排列key的Map。
个人感受:
通过一个周的学习,我参考数据结构中的知识,掌握了java中集合的概念,学习了集合的知识以及使用方法。另外,通过新的学习方式,结对编程,我们更加轻松的完成了编程任务,并与合作伙伴之间提出了积极的程序改进建议。在学习中,本人对HashMap和TreeMap仍然不是很懂,望老师能够进行回顾。