一:理论知识部分:
(1)集合:集合(Collection或称为容器)是一种包含多个元素并提供对所包含元素操作方法的类,其包含的元素可以由同一类型的对象组成,也可以由不同类型的对象组成。
A:集合类的作用:
– Java的集合类提供了一些基本数据结构的支持。
– 例如Vector、Hashtable、Stack等。
. 集合类的使用:
– Java的集合类包含在java.util包中。
– import java.util.*;
B:集合类的特点:1 只容纳对象(数组可以容纳基本数据类型数据和对象。)
2集合类容纳的对象都是Object类的实例,一旦把一个对象置入集合类中,它的类信息将丢失,这样设计的目的是为了集合类的通用性。
– 因为Object类是所有类的祖先,所以可以在这些集合中存放任何类的对象而不受限制,但切记在使用集合成员之前必须对它重新造型。
(2)vector类
Vector类类似长度可变的数组。
Vector中只能存放对象。
Vector的元素通过下标进行访问。
Vector类关键属性:
– capacity表示集合最多能容纳的元素个数。
– capacityIncrement表示每次增加多少容量。
– size表示集合当前元素个数。
(3)Stack类
Stack类是Vector的子类。
Stack类描述堆栈数据结构,即LIFO。
(4)Hashtable类。
Hashtable通过键来查找元素。
Hashtable用散列码(hashcode)来确定键。所
有对象都有一个散列码,可以通过Object类的
hashCode()方法获得。.
(5).集合框架中的基本接口:
A:Collection:集合层次中的根接口,JDK未提供这个接口的直接实现类。
B:Set:不能包含重复的元素。对象可能不是按存放的次序存放,也就是说不能像数组一样按索引的方式进行访问,SortedSet是一个按照升序排列元素的Set。
C:List:是一个有序的集合,可以包含重复的元素。提供了按索引访问的方式。
D:Map:包含了key-value对。Map不能包含重复的key。
E:SortedMap是一个按照升序排列key的Map。
(6)ArrayList
ArrayList:可以将其看作是能够自动增长容量的数组。
. 利用ArrayList的toArray()返回一个数组。
. Arrays.asList()返回一个列表。
. LinkedList是采用双向循环链表实现的。
. 利用LinkedList实现栈(stack)、队列(queue)、双向队列(double-ended queue )。
. ArrayList底层采用数组完成,而LinkedList则是以一般的双向链表(double-linked list)完成,其内每个对象除了数据本身外,还有两个引用,分别指向前一个元素和后一个元素。
. 如果经常在List 中进行插入和删除操作, 应该使用LinkedList,否则,使用ArrayList将更加快速。
(7)set
Set中的元素必须唯一。
. 添加到Set中的对象元素必须定义equals方法,以提供算法来判断欲添加进来的对象是否与已经存在的某对象相等,从而建立对象的唯一性。
. 实现Set 接口的类有HashSet,TreeSet。
(8)Map接口的方法
boolean containsKey(Object k) 检查调用映射中是否包含关键字K
. boolean containsValue(Object v) 检查调用映射中是否包含值V
. Object get(Object k) 返回与关键字k相关联的值
. boolean isEmpty( ) 如果调用映射是空的,则返回true;否则返回false
. Object put(Object k, Object v)将一个键值对加入调用映射
. Object remove(Object k) 删除关键字等于k的键值对
. int size( ) 返回映射中关键字/值对的个数
. Set entrySet( ) 返回包含了映射中的项的集合(Set)。该集合包含了类型Map.Entry的对象。这个方法为调用映射提供了一个集合“视图”
. Set keySet( ) 返回一个包含调用映射中关键字的集合(Set)。这个方法为调用映射的关键字提供了一个集合“视图”
. Collection values( )返回一个包含了映射中的值的类集。这个方法为映射中的值提供了一个类集“视图”
(9)Map接口
Map 接口的实现类主要有HashMap ,
TreeMap,Hashtable,Properties。
. Hashtable,Properties是JDK1.0/1.1中的。
. HashMap对key进行散列。
. TreeMap按照key进行排序。
. 和Set 类似, HashMap 的速度通常都比TreeMap快,只有在需要排序的功能的时候,才使用TreeMap。
二:实验
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);
}
}
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();//创建了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++)
//instanceof用来判断内存中实际对象
if (cats.elementAt(i) instanceof Cat) {
((Cat) cats.elementAt(i)).print();
} else {
((Dog) cats.elementAt(i)).print();
}
}
}
运行结果:
修改后:
import java.util.*;
public class Stacks {
static String[] months = { "1", "2", "3", "4" };
public static void main(String\[\] args) {
Stack stk = new Stack();//创建了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());
}
}
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();//创建了Hashtable类
for (int i = 0; i < 10000; i++) {
//用整形包装器生成了20个随机数
Integer r = new Integer((int) (Math.random() * 20));
//通过对象调用containskey方法
if (ht.containsKey(r))
//判断r值是不是ht里的健值,如果是返回ture,不是返回Flash
((Counter) ht.get(r)).i++;
else
//通过Counter类对象引用类内部的属性
ht.put(r, new Counter());
//调用put方法向hash表中添加信息(缺省的构造器,其属性值是初始值1
}
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");
}
}
import java.util.*;
public class ArrayListDemo {
public static void main(String[] argv) {
ArrayList al = new ArrayList();//创建了Arraylist数组
// Add lots of elements to the ArrayList…
//用Add来添加对象且可以重载
al.add(new Integer(11));//在当前位置添加一个元素11
al.add(new Integer(12));
al.add(new Integer(13));
al.add(new String("hello"));
System.out.println(al.size());
//首先用一个For循环打印出来
// 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();//构建LinkedList链表类
l.add(new Object());//在当前位置添加一个对象
l.add("Hello");
l.add("zhangsan");
System.out.println(l.size());//输出l的长度
ListIterator li = l.listIterator(0);//用迭代器生成对象
while (li.hasNext())//如果存在可访问的元素可以返回ture
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。
package linkedList;
import java.util.*;
/**
* This program demonstrates operations on linked lists.
* @version 1.12 2018-04-10
* @author Cay Horstmann
*/
public class LinkedListTest
{
public static void main(String[] args)
{
var a = new LinkedList
a.add("Amy");
a.add("Carl");
a.add("Erica");
var b = new LinkedList<String>();
b.add("Bob");
b.add("Doug");
b.add("Frances");
b.add("Gloria");
// 将单词从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);
//从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());
}
}
}
package linkedList;
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)
{
var words = new HashSet
long totalTime = 0;
try (var 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.*;
/**
* An item with a description and a part number.
*/
public class Item implements Comparable
{
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;
var 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.*;
/**
* This program sorts a set of Item objects by comparing their descriptions.
* @version 1.13 2018-04-10
* @author Cay Horstmann
*/
public class TreeSetTest
{
public static void main(String[] args)
{
var 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);
var sortByDescription = new TreeSet<Item>(
Comparator.comparing(Item::getDescription));
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
测试程序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);
}
}
import java.util.*;
public class HashMapDemo {
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,结合程序运行结果理解程序;
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)
{
var 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,结合使用体验对所运行程序提出完善建议;
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.Scanner;
public class M{
private static ArrayList
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();
Test student = new Test();
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("1:字典排序");
System.out.println("2:输出年龄最大和年龄最小的人");
System.out.println("3:寻找老乡");
System.out.println("4:寻找年龄相近的人");
System.out.println("5:退出");
String m = scanner.next();
switch (m) {
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("province?");
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("province"+studentlist.get(i));
}
break;
case "4":
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near=agematched(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 agematched(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;
}
}
public class Test implements Comparable
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) {
this.age= age;
}
public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
}
public int compareTo(Test o) {
return this.name.compareTo(o.getName());
}
public String toString() {
return name+"\\t"+sex+"\\t"+age+"\\t"+number+"\\t"+province+"\\n";
}
}
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
package 练习2;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Suanshu1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Suanshu Suanshu=new Suanshu();
PrintWriter output = null;
try {
output = new PrintWriter("ss.txt");
} catch (Exception e) {
//e.printStackTrace();
}
int sum = 0;
for (int i = 1; i < 11; i++) {
int a = (int) Math.round(Math.random() \* 100);
int b = (int) Math.round(Math.random() \* 100);
int s = (int) Math.round(Math.random() \* 3);
switch(s)
{
case 1:
System.out.println(i+": "+a+"/"+b+"=");
while(b==0){
b = (int) Math.round(Math.random() \* 100);
}
double c = in.nextDouble();
output.println(a+"/"+b+"="+c);
if (c == Suanshu.chu\_fa(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
break;
case 2:
System.out.println(i+": "+a+"\*"+b+"=");
int c1 = in.nextInt();
output.println(a+"\*"+b+"="+c1);
if (c1 == Suanshu.chen\_fa(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
break;
case 3:
System.out.println(i+": "+a+"+"+b+"=");
int c2 = in.nextInt();
output.println(a+"+"+b+"="+c2);
if (c2 == Suanshu.jia\_fa(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
break ;
case 4:
System.out.println(i+": "+a+"-"+b+"=");
int c3 = in.nextInt();
output.println(a+"-"+b+"="+c3);
if (c3 == Suanshu.jian\_fa(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
break ;
}
}
System.out.println("成绩"+sum);
output.println("成绩:"+sum);
output.close();
}
}
package 练习2;
public class Suanshu
{
private int a;
private int b;
public int jia_fa(int a,int b)
{
return a+b;
}
public int jian_fa(int a,int b)
{
if((a-b)<0)
return 0;
else
return a-b;
}
public int chen_fa(int a,int b)
{
return a*b;
}
public int chu_fa(int a,int b)
{
if(b!=0)
return a/b;
else
return 0;
}
}
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
package ID;
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{
private static ArrayList<People> Peoplelist;
public static void main(String\[\] args) {
Peoplelist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("D:\\\\java\\\\1\\\\身份证号.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 place =linescanner.nextLine();
People People = new people();
People.setname(name);
People.setID(ID);
People.setsex(sex);
int a = Integer.parseInt(age);
People.setage(a);
People.setbirthplace(place);
Peoplelist.add(People);
}
} catch (FileNotFoundException e) {
System.out.println("查找不到信息");
e.printStackTrace();
} catch (IOException e) {
System.out.println("信息读取有误");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("————————————————————————————————————————");
System.out.println("1:按姓名字典序输出人员信息");
System.out.println("2:查询最大年龄人员信息和最小年龄人员信息");
System.out.println("3:输入你的年龄,查询年龄与你最近人的所有信息");
System.out.println("4:查询人员中是否有你的同乡");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
Collections.sort( Peoplelist);
System.out.println( Peoplelist.toString());
break;
case 2:
int max=0,min=100;int j,k1 = 0,k2=0;
for(int i=1;i< Peoplelist.size();i++)
{
j= Peoplelist.get(i).getage();
if(j>max)
{
max=j;
k1=i;
}
if(j<min)
{
min=j;
k2=i;
}
}
System.out.println("年龄最大:"+ Peoplelist.get(k1));
System.out.println("年龄最小:"+ Peoplelist.get(k2));
break;
case 3:
System.out.println("place?");
String find = scanner.next();
String place=find.substring(0,3);
String place2=find.substring(0,3);
for (int i = 0; i < Peoplelist.size(); i++)
{
if( Peoplelist.get(i).getbirthplace().substring(1,4).equals(place))
System.out.println(Peoplelist.get(i));
}
break;
case 4:
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near=agenear(yourage);
int d\_value=yourage-Peoplelist.get(near).getage();
System.out.println(""+Peoplelist.get(near));
/\* for (int i = 0; i < Peoplelist.size(); i++)
{
int p=Personlist.get(i).getage()-yourage;
if(p<0) p=-p;
if(p==d\_value) System.out.println(Peoplelist.get(i));
} \*/
break;
case 5:
isTrue = false;
System.out.println("退出程序!");
break;
default:
System.out.println("输入有误");
}
}
}
public static int agenear(int age) {
int min=25,d\_value=0,k=0;
for (int i = 0; i < Peoplelist.size(); i++)
{
d\_value= Peoplelist.get(i).getage()-age;
if(d\_value<0) d\_value=-d\_value;
if (d\_value<min)
{
min=d\_value;
k=i;
}
} return k;
}
}
package ID;
public abstract class People implements Comparable
private String name;
private String ID;
private int age;
private String sex;
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 int getage() {
return age;
}
public void setage(int age) {
// int a = Integer.parseInt(age);
this.age= age;
}
public String getsex() {
return sex;
}
public void setsex(String sex) {
this.sex= sex;
}
public String getbirthplace() {
return birthplace;
}
public void setbirthplace(String birthplace) {
this.birthplace= birthplace;
}
public int compareTo(People o) {
return this.name.compareTo(o.getname());
}
public String toString() {
return name+"\\t"+sex+"\\t"+age+"\\t"+ID+"\\t"+birthplace+"\\n";
}
}
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习2;
import java.io
.FileNotFoundException;
import java.io
.PrintWriter;
import java.util.Scanner;
public class jisuan{
public static void main(String\[\] args) {
Scanner in = new Scanner(System.in
);
Caculator1 computing=new Caculator1();
PrintWriter output = null;
try {
output = new PrintWriter("Caculator.txt");
} catch (Exception e) {
}
int sum = 0;
for (int i = 1; i < 11; i++) {
int a = (int) Math.round(Math.random() \* 100);
int b = (int) Math.round(Math.random() \* 100);
int s = (int) Math.round(Math.random() \* 3);
switch(s)
{
case 1:
System.out.println(i+": "+a+"/"+b+"=");
while(b==0){
b = (int) Math.round(Math.random() \* 100);
}
double c = in.nextDouble();
output.println(a+"/"+b+"="+c);
if (c == (double)computing.division(a, b)) {
sum += 10;
System.out.println("正确");
}
else {
System.out.println("错误");
}
break;
case 2:
System.out.println(i+": "+a+"\*"+b+"=");
int c1 = in.nextInt();
output.println(a+"\*"+b+"="+c1);
if (c1 == computing.multiplication(a, b)) {
sum += 10;
System.out.println("正确");
}
else {
System.out.println("错误");
}
break;
case 3:
System.out.println(i+": "+a+"+"+b+"=");
int c2 = in.nextInt();
output.println(a+"+"+b+"="+c2);
if (c2 == computing.addition(a, b)) {
sum += 10;
System.out.println("正确");
}
else {
System.out.println("错误");
}
break ;
case 4:
System.out.println(i+": "+a+"-"+b+"=");
int c3 = in.nextInt();
output.println(a+"-"+b+"="+c3);
if (c3 == computing.subtraction(a, b)) {
sum += 10;
System.out.println("正确");
}
else {
System.out.println("错误");
}
break ;
}
}
System.out.println("scores:"+sum);
output.println("scores:"+sum);
output.close();
}
}
实验总结:本章先回顾了数据结构中的相关知识,然后介绍集合类的特点及作用,通过实验验证了vector类,stack类,hashtable等的用法,在周四的实验课上,在学长的示范下,初次知道了instanceof的用法,换言之了解API是根本,在不会相关的知识时及时查询,接下来就要好好复习数据结构的内容了,因为掌握的不好。
手机扫一扫
移动阅读更方便
你可能感兴趣的文章