实验十一 集合
实验时间 2018-11-8
1、实验目的与要求
(1) 掌握Vetor、Stack、Hashtable三个类的用途及常用API;
Vector类实现了长度可变的数组。
Stack类是Vector的子类。
Hashtable通过键来查找元素。 Hashtable用一个特殊的值来确定键,名为hashcode(散列码)。所有对象都有一个散列码,可以通过Object 类的hashCode()方法获得。
(2) 了解java集合框架体系组成;
集合框架为程序员提供了一个功能强大的设计方案以解决编程过程中面临的大多数任务。下一次当你需要存储和检索信息时,可考虑使用类集。记住,类集不仅仅是专为那些“大型作业”,例如联合数据库,邮件列表或产品清单系统等所专用的。它们对于一些小型作业也是很有效的。例如,TreeMap可以给出一个很好的类集以保留一组文件的字典结构。TreeSet在存储工程管理信息时是十分有用的。坦白地说,对于采用基于类集的解决方案而受益的问题种类只受限于你的想象力。
(3) 掌握ArrayList、LinkList两个类的用途及常用API。
ArrayList内存中是顺序存储的。
LinkedList内存中是以链表方式存储的。
将线性表中的数据元素依次存放在某个存储区域中,所形成的表称为顺序表。一维数组就是用顺序方式存储的线性表。
ArrayList封装了一个动态再分配的对象数组,
(4) 了解HashSet类、TreeSet类的用途及常用API。
HashSet扩展AbstractSet并且实现Set接口。它创建一个使用散列表存储的集合。散列表(hash table)是通过使用称为散列法的机制来存储信息的。在散列法中,键的信息内容用于确定一个唯一的值,称为它的散列码。然后散列码作为与键相关的数据存储之处的索引使用。键到它的散列码的转化是自动完成的,我们不会看到散列码本身,同样,散列码也不能直接索引散列表。
(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。
//示例程序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); } } |
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) { //instanceof判断类型是否匹配
((Cat) cats.elementAt(i)).print();
}
else {
((Dog) cats.elementAt(i)).print();
}
}
}
测试程序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"); } } |
import java.util.*; public class ArrayListDemo {
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"));//字符串类对象,说明集合中的元素的类型可以不同
// 首先使用for循环将它们打印出来。
System.out.println("Retrieving by index:");
for (int i = 0; i < al.size(); i++) {
System.out.println("Element " + i + " = " + al.get(i));
}
}
}
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)
{
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();//一开始迭代器(Iterator)在所有元素的左边,调用next()之后,迭代器移到第一个和第二个元素之间,next()方法返回迭代器刚刚经过的元素。 while (bIter.hasNext())
{
if (aIter.hasNext()) aIter.next();
aIter.add(bIter.next());
} System.out.println(a); // remove every second word from b bIter = b.iterator();
while (bIter.hasNext())
{
bIter.next(); // skip one element
if (bIter.hasNext())
{
bIter.next(); // skip next element
bIter.remove(); // remove that element
}
} System.out.println(b); // bulk operation: remove all words in b from a a.removeAll(b); System.out.println(a);
}
}
测试程序3:
l 运行SetDemo程序,结合运行结果理解程序;
import java.util.*; public class SetDemo { public static void main(String[] argv) { HashSet h = new HashSet(); //也可以 Set h=new HashSet() h.add("One"); h.add("Two"); h.add("One"); // DUPLICATE h.add("Three"); Iterator it = h.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } |
l 在Elipse环境下调试教材365页程序9-2,结合运行结果理解程序;了解HashSet类的用途及常用API。
l 在Elipse环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用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.");
}
}
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);
}
}
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,结合程序运行结果理解程序;
l 了解HashMap、TreeMap两个类的用途及常用API。
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 + "]";
}
}
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));
}
}
实验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 test1; 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.Collections;
import java.util.Scanner; public class Main{
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("F:\\身份证号.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" ");
String name = linescanner.next();
String number = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String province =linescanner.nextLine();
Student student = new Student();
student.setName(name);
student.setnumber(number);
student.setsex(sex);
int a = Integer.parseInt(age);
student.setage(a);
student.setprovince(province);
studentlist.add(student); }
} catch (FileNotFoundException e) {
System.out.println("学生信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("学生信息文件读取错误");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("选择你的操作,输入正确格式的选项");
System.out.println("A.按姓名字典排序");
System.out.println("B.输出年龄最大和年龄最小的人");
System.out.println("C.寻找老乡");
System.out.println("D.寻找年龄相近的人");
System.out.println("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 test1; public class Student implements Comparable<Student> { private String name;
private String number ;
private String sex ;
private int age;
private String province; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getsex() {
return sex ;
}
public void setsex(String sex ) {
this.sex =sex ;
}
public int getage() { return age;
}
public void setage(int age) {
// int a = Integer.parseInt(age);
this.age= age;
} public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
} public int compareTo(Student o) {
return this.name.compareTo(o.getName());
} public String toString() {
return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
}
}
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
package shiyan;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter; public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
PrintWriter output = null;
try {
output = new PrintWriter("E:/test.txt");
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
System.out.println("文件输出失败");
e.printStackTrace();
}
int sum=0;
jisuanji js=new jisuanji();
for (int i = 0; i < 10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int n = (int) Math.round(Math.random() * 4 ); switch(n)
{
case 1:
System.out.println(a+"/"+b+"=");
while(b==0){
b = (int) Math.round(Math.random() * 100);
}
while(a%b!=0) {
a = (int) Math.round(Math.random() * 100);
b = (int) Math.round(Math.random() * 100);
}
double c = in.nextDouble();
output.println(a+"/"+b+"="+c);
if (c == js.chu(a,b)) {
sum += 10;
System.out.println("答案正确");
}
else {
System.out.println("答案错误");
} break; case 2:
System.out.println(a+"*"+b+"=");
int c1 = in.nextInt();
output.println(a+"*"+b+"="+c1);
if (c1 == js.chen(a, b)) {
sum += 10;
System.out.println("答案正确");
}
else {
System.out.println("答案错误");
}
break;
case 3:
System.out.println(a+"+"+b+"=");
int c2 = in.nextInt();
output.println(a+"+"+b+"="+c2);
if (c2 == js.jia(a, b)) {
sum += 10;
System.out.println("答案正确");
}
else {
System.out.println("答案错误");
} break ;
case 4:
System.out.println(a+"-"+b+"=");
while(a<b) {
a = (int) Math.round(Math.random() * 100);
b = (int) Math.round(Math.random() * 100);
}
int c3 = in.nextInt();
output.println(a+"-"+b+"="+c3);
if (c3 == js.jian(a,b)) {
sum += 10;
System.out.println("答案正确");
}
else {
System.out.println("答案错误");
}
break ; } }
System.out.println("成绩"+sum);
output.println("成绩:"+sum);
output.close();
}
}
package shiyan; public class jisuanji<T> {
private T a;
private T b;
public jisuanji() {
a=null;
b=null;
}
public jisuanji(T a,T b) {
this.a=a;
this.b=b;
}
public int jia(int a,int b)
{
return a+b;
}
public int jian(int a,int b)
{
return a-b;
}
public int chen(int a,int b)
{
return a*b;
}
public int chu(int a,int b)
{
if(b!=0&&a%b==0)
return a/b;
else
return 0;
}
}
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
package test1; 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.Collections;
import java.util.Scanner; public class Main{
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("F:\\身份证号.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" ");
String name = linescanner.next();
String number = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String province =linescanner.nextLine();
Student student = new Student();
student.setName(name);
student.setnumber(number);
student.setsex(sex);
int a = Integer.parseInt(age);
student.setage(a);
student.setprovince(province);
studentlist.add(student); }
} catch (FileNotFoundException e) {
System.out.println("学生信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("学生信息文件读取错误");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("选择你的操作,输入正确格式的选项");
System.out.println("A.按姓名字典排序");
System.out.println("B.输出年龄最大和年龄最小的人");
System.out.println("C.寻找老乡");
System.out.println("D.寻找年龄相近的人");
System.out.println("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 test1; public class Student implements Comparable<Student> { private String name;
private String number ;
private String sex ;
private int age;
private String province; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getsex() {
return sex ;
}
public void setsex(String sex ) {
this.sex =sex ;
}
public int getage() { return age;
}
public void setage(int age) {
// int a = Integer.parseInt(age);
this.age= age;
} public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
} public int compareTo(Student o) {
return this.name.compareTo(o.getName());
} public String toString() {
return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
}
}
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习2。
package shiyan;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter; public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
PrintWriter output = null;
try {
output = new PrintWriter("E:/test.txt");
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
System.out.println("文件输出失败");
e.printStackTrace();
}
int sum=0;
jisuanji js=new jisuanji();
for (int i = 0; i < 10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int n = (int) Math.round(Math.random() * 4 ); switch(n)
{
case 1:
System.out.println(a+"/"+b+"=");
while(b==0){
b = (int) Math.round(Math.random() * 100);
}
while(a%b!=0) {
a = (int) Math.round(Math.random() * 100);
b = (int) Math.round(Math.random() * 100);
}
double c = in.nextDouble();
output.println(a+"/"+b+"="+c);
if (c == js.chu(a,b)) {
sum += 10;
System.out.println("答案正确");
}
else {
System.out.println("答案错误");
} break; case 2:
System.out.println(a+"*"+b+"=");
int c1 = in.nextInt();
output.println(a+"*"+b+"="+c1);
if (c1 == js.chen(a, b)) {
sum += 10;
System.out.println("答案正确");
}
else {
System.out.println("答案错误");
}
break;
case 3:
System.out.println(a+"+"+b+"=");
int c2 = in.nextInt();
output.println(a+"+"+b+"="+c2);
if (c2 == js.jia(a, b)) {
sum += 10;
System.out.println("答案正确");
}
else {
System.out.println("答案错误");
} break ;
case 4:
System.out.println(a+"-"+b+"=");
while(a<b) {
a = (int) Math.round(Math.random() * 100);
b = (int) Math.round(Math.random() * 100);
}
int c3 = in.nextInt();
output.println(a+"-"+b+"="+c3);
if (c3 == js.jian(a,b)) {
sum += 10;
System.out.println("答案正确");
}
else {
System.out.println("答案错误");
}
break ; } }
System.out.println("成绩"+sum);
output.println("成绩:"+sum);
output.close();
}
}
package shiyan; public class jisuanji<T> {
private T a;
private T b;
public jisuanji() {
a=null;
b=null;
}
public jisuanji(T a,T b) {
this.a=a;
this.b=b;
}
public int jia(int a,int b)
{
return a+b;
}
public int jian(int a,int b)
{
return a-b;
}
public int chen(int a,int b)
{
return a*b;
}
public int chu(int a,int b)
{
if(b!=0&&a%b==0)
return a/b;
else
return 0;
}
}
实验总结:
对数据结构中的一些基本类型有了进一步的了解,通过注释,编译逐渐理解了本周理论知识所讲的知识,感受到了它们的区别和联系,在本周实验中还增加了一个结对实验,这个合作实验让我们发现了彼此的不足和需要改进的地方,是 一个很好的相互学习的过程。复习了前面学过的知识细节,例如强制转换类型时进行判断的instanceof语句。初步体会了合作编程,互相提高的过程和乐趣。