理论知识部分
1.数据结构:一般将数据结构分为两大类:线性数据结构和非线性数据结构。
线性数据结构:线性表、栈、队列、串、数组和文件。
非线性数据结构:树和图。
2.JAVA的集合框架:
JAVA的集合框架实现对各种数据结构的封装,以降低对数据管理与处理的难度。所谓框架就是一个类库的集合,框架中包含很多 超类,编程者创建这些超类的子类可较方便的设 计设计程序所需的类。
集合(Collection或称为容器)是一种包含多个元素 并提供对所包含元素操作方法的类,其包含的元 素可以由同一类型的对象组成,也可以由不同类 型的对象组成。
3.集合类:
集合类的作用:Java的集合类提供了一些基本数据结构的支持。例如Vector、Hashtable、Stack等。
集合类的使用:Java的集合类包含在java.util包中。
集合类的特点:只容纳对象;
集合类容纳的对象都是Object类的实例,一旦 把一个对象置入集合类中,它的类信息将丢失 ,这样设计的目的是为了集合类的通用性。
4.Vector类:
Vector类类似长度可变的数组。
Vector中只能存放对象。
Vector的元素通过下标进行访问。
Vector类关键属性:capacity表示集合多能容纳的元素个数。
capacityIncrement表示每次增加多少容量。
size表示集合当前元素个数。
5.Stack类:
Stack类是Vector的子类。
Stack类描述堆栈数据结构,即LIFO。
6.Hashtable类:
Hashtable通过键来查找元素。
Hashtable用散列码(hashcode)来确定键。所 有对象都有一个散列码,可以通过Object类的 hashCode()方法获得。
7.集合框架中的基本接口:
Collection:集合层次中的根接口,JDK未提供这个 接口的直接实现类。
Set:不能包含重复的元素。对象可能不是按存放的 次序存放,也就是说不能像数组一样按索引的方式进 行访问,SortedSet是一个按照升序排列元素的Set。
List:是一个有序的集合,可以包含重复的元素。提 供了按索引访问的方式。
Map:包含了key-value对。Map不能包含重复的key 。
SortedMap是一个按照升序排列key的Map。
实验部分:
实验1:
测试程序1:
示例程序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();//强制类型转化 } }
出现错误,dog类不能转换成cat类,修改程序:
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();//如果能进行强制类型转换,输出为Cat else { ((Dog) cats.elementAt(i)).print();//不能则输出dog } } } }
示例程序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));//生成0到19的20个整型随机数 if (ht.containsKey(r))//判断r是否是哈希表中元素的键值 ((Counter) ht.get(r)).i++; else ht.put(r, new Counter()); } System.out.println(ht); } }
测试程序2:
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")); // 用循环语句打印 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);//通过迭代器生成对象产生方法hasNext返回 while (li.hasNext()) System.out.println(li.next()); if (l.indexOf("Hello") < 0) //判断元素是否在集合当中,如果是,返回一个大于0的值,如果不是,返回负值 System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } }
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<>();//泛型创建a链表 a.add("Amy"); a.add("Carl"); a.add("Erica"); List<String> b = new LinkedList<>();//泛型创建b链表 b.add("Bob"); b.add("Doug"); b.add("Frances"); b.add("Gloria"); // //合并a和b中的单词 ListIterator<String> aIter = a.listIterator(); Iterator<String> bIter = b.iterator(); while (bIter.hasNext()) { if (aIter.hasNext()) aIter.next(); aIter.add(bIter.next()); } System.out.println(a); // //从第二个链表中每隔一个元素删除一个元素 bIter = b.iterator(); while (bIter.hasNext()) { bIter.next(); // 跳到第一个元素
if (bIter.hasNext()) { bIter.next(); // 跳到下一个元素
bIter.remove(); // 删除该元素
} } System.out.println(b); // 批量操作: 删除从b到a的所有单词 a.removeAll(b); System.out.println(a); } }
测试程序3:
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 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 实现 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."); } }
TreeSetTest.java
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));//自定义类对象存入TreeSet排序 sortByDescription.addAll(parts); System.out.println(sortByDescription); } }
Item.java
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:
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); } }
MapTest.java
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")); // 打印所有条目 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)); } }
Employee.java
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:结对编程练习:
本次实验结对编程合作伙伴:冯志霞
实验九编程练习1:
package fzx; 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 A{ private static ArrayList<Test> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("D:\身份证号.txt"); try { FileInputStream fis = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" "); String name = linescanner.next(); String number = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String province =linescanner.nextLine(); 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; } }
package fzx; public class Test implements Comparable<Test> { 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+" "+sex+" "+age+" "+number+" "+province+" "; } }
运行结果:
我认为这个程序在输出要求方面没有错误,如果代码能够更加规范,简洁就很好了
实验十编程练习2:
package 算术; import java.util.Random; import java.util.Scanner; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Main{ public static void main(String[] args) { yunsuan counter=new yunsuan();//与其它类建立联系 PrintWriter out=null; try { out=new PrintWriter("D:/text.txt");//将文件里的内容读入到D盘名叫text的文件中 }catch(FileNotFoundException e) { System.out.println("文件找不到"); e.printStackTrace(); } int sum=0; for(int i=0;i<10;i++) { int a=new Random().nextInt(100); int b=new Random().nextInt(100); Scanner in=new Scanner(System.in); //in.close(); switch((int)(Math.random()*4)) { case 0: System.out.println( ""+a+"+"+b+"="); int c1 = in.nextInt(); out.println(a+"+"+b+"="+c1); if (c1 == counter.plus(a, b)) { sum += 10; System.out.println("答案正确"); } else { System.out.println("答案错误"); } break ; case 1: if(a<b) { int temp=a; a=b; b=temp; }//为避免减数比被减数大的情况 System.out.println(""+a+"-"+b+"="); /*while((a-b)<0) { b = (int) Math.round(Math.random() * 100); }*/ int c2 = in.nextInt(); out.println(a+"-"+b+"="+c2); if (c2 == counter.minus(a, b)) { sum += 10; System.out.println("答案正确"); } else { System.out.println("答案错误"); } break ; case 2: System.out.println(""+a+"*"+b+"="); int c = in.nextInt(); out.println(a+"*"+b+"="+c); if (c == counter.multiply(a, b)) { sum += 10; System.out.println("答案正确"); } else { System.out.println("答案错误"); } break; case 3: while(b==0) { b = (int) Math.round(Math.random() * 100);//满足分母不为0 } while(a%b!=0) { a = (int) Math.round(Math.random() * 100); b = (int) Math.round(Math.random() * 100); } System.out.println(""+a+"/"+b+"="); int c0= in.nextInt(); out.println(a+"/"+b+"="+c0); if (c0 == counter.divide(a, b)) { sum += 10; System.out.println("答案正确"); } else { System.out.println("答案错误"); } break; } } System.out.println("totlescore:"+sum); out.println(sum); out.close(); } }
package 算术; public class yunsuan <T>{ private T a; private T b; public void yunsaun() { a=null; b=null; } public void yunsuan(T a,T b) { this.a=a; this.b=b; } public int plus(int a,int b) { return a+b; } public int minus(int a,int b) { return a-b; } public int multiply(int a,int b) { return a*b; } public int divide(int a,int b) { if(b!=0 && a%b==0) return a/b; else return 0; } }
运行结果:
我认为这个程序在输出结果方面没有错误,相较于我的程序更加完善,在文件导出方面比我做的要好。
与学习伙伴合作完成实验九编程练习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 A{ private static ArrayList<Test> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("D:\身份证号.txt"); try { FileInputStream fis = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" "); String name = linescanner.next(); String number = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String province =linescanner.nextLine(); 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<Test> { 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+" "+sex+" "+age+" "+number+" "+province+" "; } }
输出结果:
与学习伙伴合作完成实验十编程练习2:
package 算术; import java.util.Random; import java.util.Scanner; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Main{ public static void main(String[] args) { yunsuan counter=new yunsuan();//与其它类建立联系 PrintWriter out=null; try { out=new PrintWriter("D:/text.txt");//将文件里的内容读入到D盘名叫text的文件中 }catch(FileNotFoundException e) { System.out.println("文件找不到"); e.printStackTrace(); } int sum=0; for(int i=0;i<10;i++) { int a=new Random().nextInt(100); int b=new Random().nextInt(100); Scanner in=new Scanner(System.in); //in.close(); switch((int)(Math.random()*4)) { case 0: System.out.println( ""+a+"+"+b+"="); int c1 = in.nextInt(); out.println(a+"+"+b+"="+c1); if (c1 == counter.plus(a, b)) { sum += 10; System.out.println("答案正确"); } else { System.out.println("答案错误"); } break ; case 1: if(a<b) { int temp=a; a=b; b=temp; }//为避免减数比被减数大的情况 System.out.println(""+a+"-"+b+"="); /*while((a-b)<0) { b = (int) Math.round(Math.random() * 100); }*/ int c2 = in.nextInt(); out.println(a+"-"+b+"="+c2); if (c2 == counter.minus(a, b)) { sum += 10; System.out.println("答案正确"); } else { System.out.println("答案错误"); } break ; case 2: System.out.println(""+a+"*"+b+"="); int c = in.nextInt(); out.println(a+"*"+b+"="+c); if (c == counter.multiply(a, b)) { sum += 10; System.out.println("答案正确"); } else { System.out.println("答案错误"); } break; case 3: while(b==0) { b = (int) Math.round(Math.random() * 100);//满足分母不为0 } while(a%b!=0) { a = (int) Math.round(Math.random() * 100); b = (int) Math.round(Math.random() * 100); } System.out.println(""+a+"/"+b+"="); int c0= in.nextInt(); out.println(a+"/"+b+"="+c0); if (c0 == counter.divide(a, b)) { sum += 10; System.out.println("答案正确"); } else { System.out.println("答案错误"); } break; } } System.out.println("你的总分为:"+sum); out.println(sum); out.close(); } }
package 算术; public class yunsuan <T>{ private T a; private T b; public void yunsaun() { a=null; b=null; } public void yunsuan(T a,T b) { this.a=a; this.b=b; } public int plus(int a,int b) { return a+b; } public int minus(int a,int b) { return a-b; } public int multiply(int a,int b) { return a*b; } public int divide(int a,int b) { if(b!=0 && a%b==0) return a/b; else return 0; } }
输出结果:
实验总结:
通过这周的学习,让我印象最深的是和同学组队进行编程的过程,通过参照学习伙伴的实验程序,我知道了我之前的程序的错误,比如在第二个编程实在计算题导出的地方我知道了自己的错误在哪,而且我的队友也很认真的给我讲解了我一直困惑的问题。和别人对比我才知道自己和别人的差距,比起之前的实验,有了更多和别人的交流,一起讨论,结合两个人的意见经验,对于代码有不同的看法,能对代码有不同的意见,是一次收获颇多的学习。