zoukankan      html  css  js  c++  java
  • 201771010111李瑞红《第十一周学习总结》

    实验十一   集合

    实验时间 2018-11-8

    第一部分:理论总结

    1.栈(Stack)也是一种特殊的线性表,是一种后进先出 (LIFO)的结构。栈是限定仅在表尾进行插入和删除运算的线性表,表尾称为栈顶(top),表头称为(bottom)。栈的物理存储可以用顺序存储结构,也可以用链式存储结构。

    2.队列(Queue)是限定所有的插入只能在表的一端进行 ,而所有的删除都在表的另一端进行的线性表。表中允许插入的一端称为队尾(Rear),允许删除的一端称为队头(Front)。队列的操作是按先进先出(FIFO)的原则进行的。队列的物理存储可以用顺序存储结构,也可以用链式存储结构。

    3.一般将数据结构分为两大类:线性数据结构和非线性数据结构。线性数据结构:线性表、栈、队列、串、数组和文件。非线性数据结构:树和图。线性表按其存储结构可分为顺序表和链表;用顺序存储结构存储的线性表称为顺序表;顺序表将线性表中的数据元素依次存放在某个存储区域中。一维数组就是用顺序方式存储的线性表。用链式存储结构存储的线性表称为链表。

    4.集合框架:JAVA集合类库的统一架构。集合类的作用:Java的集合类提供了一些基本数据结构的支持。集合类的使用: Java的集合类包含在java.util包中。集合类的特点一:只容纳对象。注意:数组可以容纳基本数据类型数据和对象。如果集合类中想使用基本数据类型,又想利用集合类的灵活性,可以把基本数据类型数据封装成该数据类型的包装器对象,然后放入集合中处理。特点二:集合类容纳的对象都是Object类的实例,一旦把一个对象置入集合类中,它的类信息将丢失,这样设计的目的是为了集合类的通用性。因为Object类是所有类的祖先,所以可以在这些集合中存放任何类的对象而不受限制,但在使用集合成员之前必须对它重新造型。

    5.JAVA的集合框架实现对各种数据结构的封装,以降低对数据管理与处理的难度。所谓框架就是一个类库的集合,框架中包含很多超类,编程者创建这些超类的子类可较方便的设计设计程序所需的类。

    6.Map接口用来维持很多“键-值”对,以便通过键来查找相应的值。HashMap基于散列表实现(替代Hashtable)。TreeMap在一个二叉树的基础上实现(map)是一个存储关键字和值的关联或关键字/值对的对象。给定一个关键字,可以得到它的值。关键字和值都是对象。关键字必须是唯一的。但值是可以被复制的。Map接口映射唯一关键字到值。关键字(key)是以后用于检索值的对象。给定一个关键字和一个值,可以存储这个值到一个Map对象中。当这个值被存储以后,就可以使用它的关键字来检索它,Map循环使用两个基本操作:get( )和put( )。使用 put( )方法可以将一个指定了关键字和值的值加入映射。为了得到值可以通过将关键字作为参数来调用 get( )方法。调用返回该值。Map接口的实现类主要有HashMap,TreeMap,Hashtable,Properties。HashMap对key进行散TreeMap按照key进行排序。和Set类似,HashMap的速度通常都比TreeMap快,只有在需要排序的功能的时候,才使用TreeMap。

    7.Vector类类似长度可变的数组。Vector中只能存放对象。Vector的元素通过下标进行访问。 Vector类关键属性:capacity表示集合最多能容纳的元素个数。capacityIncrement表示每次增加多少容量。size表示集合当前元素个数。Stack类是Vector的子类。Stack类描述堆栈数据结构,即LIFO。Hashtable通过键来查找元素。Hashtable用散列码(hashcode)来确定键。所有对象都有一个散列码,可以通过Object类的hashCode()方法获得。

    8.集合框架中的基本接口:Collection:集合层次中的根接口,JDK未提供这个接口的直接实现类。

    Set:不能包含重复的元素。对象可能不是按存放的次序存放,也就是说不能像数组一样按索引的方式进行访问,SortedSet是一个按照升序排列元素的Set。List的明显特征是它的元素都有一个确定的顺序。实现它的类有ArrayList和LinkedList。ArrayList中的元素在内存中是顺序存储的。LinkedList中的元素在内存中是以链表方式存储的。

    TreeSet是一个有序集合,TreeSet中元素将照升序排列,缺省是按照自然顺序进行排列,意味着TreeSet中元素要实现Comparable接口。可以在构造TreeSet对象时,传递实现了 Comparator接口的比较器对象。HashSet是基于Hash算法实现的,其性能通常都优于TreeSet。通常使用HashSet,需要排序的功能时,使用TreeSet。

    第二部分:实验

    1、实验目的与要求

    (1) 掌握VetorStackHashtable三个类的用途及常用API

    (2) 了解java集合框架体系组成;

    (3) 掌握ArrayListLinkList两个类的用途及常用API

    (4) 了解HashSet类、TreeSet类的用途及常用API

    (5)了解HashMapTreeMap两个类的用途及常用API

    (6) 结对编程(Pair programming)练习,体验程序开发中的两人合作。

    2、实验内容和步骤

    实验1: 导入第9章示例程序,测试程序并进行代码注释。

    测试程序1:

    使用JDK命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;

    掌握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 //示例程序1
     2 
     3 import java.util.Vector;
     4 
     5  
     6 
     7 class Cat {
     8 
     9 private int catNumber;
    10 
    11  
    12 
    13 Cat(int i) {
    14 
    15         catNumber = i;
    16 
    17 }
    18 
    19  
    20 
    21 void print() {
    22 
    23         System.out.println("Cat #" + catNumber);
    24 
    25 }
    26 
    27 }
    28 
    29  
    30 
    31 class Dog {
    32 
    33 private int dogNumber;
    34 
    35  
    36 
    37 Dog(int i) {
    38 
    39         dogNumber = i;
    40 
    41 }
    42 
    43  
    44 
    45 void print() {
    46 
    47         System.out.println("Dog #" + dogNumber);
    48 
    49 }
    50 
    51 }
    52 
    53  
    54 
    55 public class CatsAndDogs {
    56 
    57 public static void main(String[] args) {
    58 
    59         Vector cats = new Vector();
    60 
    61         for (int i = 0; i < 7; i++)
    62 
    63                cats.addElement(new Cat(i));
    64 
    65         cats.addElement(new Dog(7));
    66 
    67         for (int i = 0; i < cats.size(); i++)
    68 
    69                ((Cat) cats.elementAt(i)).print();
    70 
    71 }
    72 
    73 }

    运行结果

    改进程序

     1 package ccc;
     2 
     3     import java.util.Vector;
     4 
     5     class Cat {
     6         private int catNumber;
     7 
     8         Cat(int i) {
     9             catNumber = i;
    10         }
    11 
    12         void print() {
    13             System.out.println("Cat #" + catNumber);
    14         }
    15     }
    16 
    17     class Dog {
    18         private int dogNumber;
    19 
    20         Dog(int i) {
    21             dogNumber = i;
    22         }
    23 
    24         void print() {
    25             System.out.println("Dog #" + dogNumber);
    26         }
    27     }
    28 
    29     public class CatsAndDogs {
    30         public static void main(String[] args) {
    31             Vector cats = new Vector();
    32             for (int i = 0; i < 7; i++)
    33                 cats.addElement(new Cat(i));
    34             cats.addElement(new Dog(7));
    35             for (int i = 0; i < cats.size(); i++) {
    36                 if(cats.elementAt(i) instanceof Cat) {
    37                  ( (Cat) cats.elementAt(i)).print();
    38             }else {
    39                 ((Dog)cats.elementAt(i)).print();
    40             }
    41             }
    42         }
    43     }
    44     

    结果

     示例2:

    原程序:

     1 //示例程序2
     2 
     3 import java.util.*;
     4 
     5  
     6 
     7 public class Stacks {
     8 
     9    static String[] months = { "1", "2", "3", "4" };
    10 
    11  
    12 
    13    public static void main(String[] args) {
    14 
    15       Stack stk = new Stack();
    16 
    17       for (int i = 0; i < months.length; i++)
    18 
    19          stk.push(months[i]);
    20 
    21       System.out.println(stk);
    22 
    23       System.out.println("element 2=" + stk.elementAt(2));
    24 
    25       while (!stk.empty())
    26 
    27          System.out.println(stk.pop());
    28 
    29    }
    30 
    31 }

    结果:

    实例三

     1 import java.util.*;
     2 
     3 class Counter {
     4     int i = 1;
     5     public String toString() {
     6         return Integer.toString(i);//将i转换成tostring类
     7     }
     8 }
     9 public class Statistics {
    10     public static void main(String[] args) {
    11         Hashtable ht = new Hashtable();//生成Hashtable类
    12         for (int i = 0; i < 10000; i++) {
    13             Integer r = new Integer((int) (Math.random() * 20));//用Math.random生成20以内的随机数
    14             if (ht.containsKey(r))//通过ht对象调用containsKey方法
    15                 ((Counter) ht.get(r)).i++;//通过Counter类对象引用它的属性
    16             else
    17                 ht.put(r, new Counter());
    18         }
    19         System.out.println(ht);
    20     }
    21 }

    测试程序2:

    使用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");

       }

    }

    源代码

     1 package ccc;
     2 import java.util.*;
     3 public class ArrayListDemo {
     4 public static void main(String[] argv) {
     5 ArrayList<Comparable> al = new ArrayList();
     6 // 给Arraylist里面添加元素
     7 al.add(new Integer(11));
     8 al.add(new Integer(12));
     9 al.add(new Integer(13));
    10 al.add(new String("hello"));
    11 // 通过for循环打印输出
    12 System.out.println(al.size());
    13 
    14 System.out.println("Retrieving by index:");
    15 for (int i = 0; i<al.size(); i++) {
    16 System.out.println("Element " + i + " = " + al.get(i));
    17 }
    18 }
    19 }

    实验结果

    源代码

     1 package ccc;
     2 import java.util.*;
     3 public class LinkedListDemo {
     4     public static void main(String[] argv) {
     5         LinkedList l = new LinkedList();
     6         l.add(new Object());//调用LinkedList的add方法
     7         l.add("Hello");
     8         l.add("zhangsan");
     9         ListIterator li = l.listIterator(0);//
    10         while (li.hasNext())
    11             System.out.println(li.next());
    12         if (l.indexOf("Hello") < 0)//判断元素是否在集合中 
    13             System.err.println("Lookup does not work");
    14         else
    15             System.err.println("Lookup works");
    16    }
    17 }

    实验结果

    在Elipse环境下编辑运行调试教材360页程序9-1,结合程序运行结果理解程序;

    掌握ArrayList、LinkList两个类的用途及常用API。

     1 import java.util.*;
     2 
     3 /**
     4  * This program demonstrates operations on linked lists.
     5  * @version 1.11 2012-01-26
     6  * @author Cay Horstmann
     7  */
     8 public class LinkedListTest
     9 {
    10    public static void main(String[] args)
    11    {
    12        //创建a和b两个链表
    13       List<String> a = new LinkedList<>();//泛型
    14       a.add("Amy");
    15       a.add("Carl");
    16       a.add("Erica");
    17 
    18       List<String> b = new LinkedList<>();//泛型
    19       b.add("Bob");
    20       b.add("Doug");
    21       b.add("Frances");
    22       b.add("Gloria");
    23 
    24       //合并a和b中的词
    25 
    26       ListIterator<String> aIter = a.listIterator();
    27       Iterator<String> bIter = b.iterator();
    28 
    29       while (bIter.hasNext())
    30       {
    31          if (aIter.hasNext()) aIter.next();
    32          aIter.add(bIter.next());
    33       }
    34 
    35       System.out.println(a);
    36 
    37       //从第二个链表中每隔一个元素删除一个元素
    38 
    39       bIter = b.iterator();
    40       while (bIter.hasNext())
    41       {
    42          bIter.next(); // 移动一个元素
    43          if (bIter.hasNext())
    44          {
    45             bIter.next(); // 移动下一个元素
    46             bIter.remove(); // 删除元素
    47          }
    48       }
    49 
    50       System.out.println(b);
    51 
    53 
    54       a.removeAll(b);
    55 
    56       System.out.println(a);//通过AbstractCollection类中的toString方法打印出链表a中的所有元素
    57    }
    58 }

    测试程序3:

    运行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());

            }

        }

    }

     1 import java.util.*;
     2 public class SetDemo {
     3     public static void main(String[] argv) {
     4         HashSet h = new HashSet(); //也可以 Set h=new HashSet()
     5         h.add("One");
     6         h.add("Two");
     7         h.add("One"); // 复制
     8         h.add("Three");
     9         Iterator it = h.iterator();
    10         while (it.hasNext()) {
    11              System.out.println(it.next());
    12         }
    13     }
    14 }

     

    在Elipse环境下调试教材365页程序9-2,结合运行结果理解程序;了解HashSet类的用途及常用API。

     1 package set;
     2 
     3 import java.util.*;
     4 
     5 /**
     6  * This program uses a set to print all unique words in System.in.
     7  * 
     8  * @version 1.12 2015-06-21
     9  * @author Cay Horstmann
    10  */
    11 public class SetTest {
    12     public static void main(String[] args) {
    13         Set<String> words = new HashSet<>(); // 对哈希表进行设置
    14         long totalTime = 0;
    15 
    16         try (Scanner in = new Scanner(System.in)) {
    17             while (in.hasNext()) {
    18                 String word = in.next();
    19                 long callTime = System.currentTimeMillis();
    20                 words.add(word);
    21                 callTime = System.currentTimeMillis() - callTime;
    22                 totalTime += callTime;
    23             }
    24         }
    25 
    26         Iterator<String> iter = words.iterator();
    27         for (int i = 1; i <= 20 && iter.hasNext(); i++)
    28             System.out.println(iter.next());
    29         System.out.println(". . .");
    30         System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
    31     }
    32 }

    在Elipse环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API。

    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);
       }
    }
     1 import java.util.*;
     2 
     3 /**
     4  * This program sorts a set of item by comparing their descriptions.
     5  * @version 1.12 2015-06-21
     6  * @author Cay Horstmann
     7  */
     8 public class TreeSetTest
     9 {
    10    public static void main(String[] args)
    11    {
    12       SortedSet<Item> parts = new TreeSet<>();
    13       parts.add(new Item("Toaster", 1234));
    14       parts.add(new Item("Widget", 4562));
    15       parts.add(new Item("Modem", 9912));
    16       System.out.println(parts);
    17 
    18       NavigableSet<Item> sortByDescription = new TreeSet<>(
    19             Comparator.comparing(Item::getDescription));//把自定义类对象存入TreeSet进行排序
    20 
    21       sortByDescription.addAll(parts);
    22       System.out.println(sortByDescription);
    23    }
    24 }

    测试程序4:

      使用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);

      }

    }

     1 import java.util.*;
     2 public class HashMapDemo //基于哈希表的 Map接口的实现,提供所有可选的映射操作
     3 {
     4    public static void main(String[] argv) {
     5       HashMap h = new HashMap();
     6       // 哈希映射从公司名称到地址
     7       h.put("Adobe", "Mountain View, CA");
     8       h.put("IBM", "White Plains, NY");
     9       h.put("Sun", "Mountain View, CA");
    10       String queryString = "Adobe";
    11       String resultString = (String)h.get(queryString);
    12       System.out.println("They are located in: " +  resultString);
    13   }
    14 }

     

    在Elipse环境下调试教材373页程序9-6,结合程序运行结果理解程序;

    了解HashMap、TreeMap两个类的用途及常用API。

     1 import java.util.*;
     2 
     3 /**
     4  * This program demonstrates the use of a map with key type String and value type Employee.
     5  * @version 1.12 2015-06-21
     6  * @author Cay Horstmann
     7  */
     8 public class MapTest
     9 {
    10    public static void main(String[] args)
    11    {
    12       Map<String, Employee> staff = new HashMap<>();
    13       staff.put("144-25-5464", new Employee("Amy Lee"));
    14       staff.put("567-24-2546", new Employee("Harry Hacker"));
    15       staff.put("157-62-7935", new Employee("Gary Cooper"));
    16       staff.put("456-62-5527", new Employee("Francesca Cruz"));
    17 
    18       // 打印所有条目
    19 
    20       System.out.println(staff);
    21 
    22       // 删除一个条目
    23 
    24       staff.remove("567-24-2546");
    25 
    26       // 替换一个条目
    27 
    28       staff.put("456-62-5527", new Employee("Francesca Miller"));
    29 
    30       // 查找一个值
    31 
    32       System.out.println(staff.get("157-62-7935"));
    33 
    34       // 遍历所有条目
    35 
    36       staff.forEach((k, v) -> 
    37          System.out.println("key=" + k + ", value=" + v));
    38    }
    39 }

    实验2:结对编程

    练习:

    关于结对编程:以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序。

     

    关于结对编程的阐述可参见以下链接:

    http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html

    http://en.wikipedia.org/wiki/Pair_programming

    对于结对编程中代码设计规范的要求参考:

    http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html

     

    以下实验,就让我们来体验一下结对编程的魅力。

    确定本次实验结对编程合作伙伴;

    各自运行合作伙伴实验九编程练习1,结合使用体验对所运行程序提出完善建议;

    各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;

    l  采用结对编程方式,与学习伙伴合作完成实验九编程练习1;

    l  采用结对编程方式,与学习伙伴合作完成实验十编程练习2。

      1 import java.io.BufferedReader;
      2 import java.io.File;
      3 import java.io.FileInputStream;
      4 import java.io.FileNotFoundException;
      5 import java.io.IOException;
      6 import java.io.InputStreamReader;
      7 import java.util.ArrayList;
      8 import java.util.Arrays;
      9 import java.util.Scanner;
     10 import java.util.Collections;//对集合进行排序、查找、修改等;
     11 
     12 public class Test {
     13     private static ArrayList<Citizen> citizenlist;
     14 
     15     public static void main(String[] args) {
     16         citizenlist = new ArrayList<>();
     17         Scanner scanner = new Scanner(System.in);
     18         File file = new File("E:/java/身份证号.txt");
     19         //异常捕获
     20         try {
     21             FileInputStream fis = new FileInputStream(file);
     22             BufferedReader in = new BufferedReader(new InputStreamReader(fis));
     23             String temp = null;
     24             while ((temp = in.readLine()) != null) {
     25 
     26                 Scanner linescanner = new Scanner(temp);
     27 
     28                 linescanner.useDelimiter(" ");
     29                 String name = linescanner.next();
     30                 String id = linescanner.next();
     31                 String sex = linescanner.next();
     32                 String age = linescanner.next();
     33                 String birthplace = linescanner.nextLine();
     34                 Citizen citizen = new Citizen();
     35                 citizen.setName(name);
     36                 citizen.setId(id);
     37                 citizen.setSex(sex);
     38                 // 将字符串转换成10进制数
     39                 int ag = Integer.parseInt(age);
     40                 citizen.setage(ag);
     41                 citizen.setBirthplace(birthplace);
     42                 citizenlist.add(citizen);
     43 
     44             }
     45         } catch (FileNotFoundException e) {
     46             System.out.println("信息文件找不到");
     47             e.printStackTrace();
     48         } catch (IOException e) {
     49             System.out.println("信息文件读取错误");
     50             e.printStackTrace();
     51         }
     52         boolean isTrue = true;
     53         while (isTrue) {
     54 
     55             System.out.println("1.按姓名字典序输出人员信息");
     56             System.out.println("2.查询最大年龄的人员信息、查询最小年龄人员信息");
     57             System.out.println("3.查询人员中是否查询人员中是否有你的同乡");
     58             System.out.println("4.输入你的年龄,查询文件中年龄与你最近人的姓名、身份证号、年龄、性别和出生地");
     59             System.out.println("5.退出");
     60             int nextInt = scanner.nextInt();
     61             switch (nextInt) {
     62             case 1:
     63                 Collections.sort(citizenlist);
     64                 System.out.println(citizenlist.toString());
     65                 break;
     66             case 2:
     67                 int max = 0, min = 100;
     68                 int m, k1 = 0, k2 = 0;
     69                 for (int i = 1; i < citizenlist.size(); i++) {
     70                     m = citizenlist.get(i).getage();
     71                     if (m > max) {
     72                         max = m;
     73                         k1 = i;
     74                     }
     75                     if (m < min) {
     76                         min = m;
     77                         k2 = i;
     78                     }
     79                 }
     80                 System.out.println("年龄最大:" + citizenlist.get(k1));
     81                 System.out.println("年龄最小:" + citizenlist.get(k2));
     82                 break;
     83             case 3:
     84                 System.out.println("出生地:");
     85                 String find = scanner.next();
     86                 String place = find.substring(0, 3);
     87                 for (int i = 0; i < citizenlist.size(); i++) {
     88                     if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place))
     89                         System.out.println("出生地" + citizenlist.get(i));
     90                 }
     91                 break;
     92             case 4:
     93                 System.out.println("年龄:");
     94                 int yourage = scanner.nextInt();
     95                 int near = peer(yourage);
     96                 int j = yourage - citizenlist.get(near).getage();
     97                 System.out.println("" + citizenlist.get(near));
     98                 break;
     99             case 5:
    100                 isTrue = false;
    101                 System.out.println("程序已退出!");
    102                 break;
    103             default:
    104                 System.out.println("输入有误");
    105             }
    106         }
    107     }
    108 
    109     public static int peer(int age) {
    110         int flag = 0;
    111         int min = 53, j = 0;
    112         for (int i = 0; i < citizenlist.size(); i++) {
    113             j = citizenlist.get(i).getage() - age;
    114             if (j < 0)
    115                 j = -j;
    116             if (j < min) {
    117                 min = j;
    118                 flag = i;
    119             }
    120         }
    121         return flag;
    122     }
    123 }
     1 public class Citizen implements Comparable<Citizen> {
     2 
     3     private String name;
     4     private String id;
     5     private String sex;
     6     private int age;
     7     private String birthplace;
     8 
     9     public String getName() {
    10         return name;
    11     }
    12 
    13     public void setName(String name) {
    14         this.name = name;
    15     }
    16 
    17     public String getId() {
    18         return id;
    19     }
    20 
    21     public void setId(String id) {
    22         this.id = id;
    23     }
    24 
    25     public String getSex() {
    26         return sex;
    27     }
    28 
    29     public void setSex(String sex) {
    30         this.sex = sex;
    31     }
    32 
    33     public int getage() {
    34         return age;
    35     }
    36 
    37     public void setage(int age) {
    38         this.age = age;
    39     }
    40 
    41     public String getBirthplace() {
    42         return birthplace;
    43     }
    44 
    45     public void setBirthplace(String birthplace) {
    46         this.birthplace = birthplace;
    47     }
    48 
    49     public int compareTo(Citizen other) {
    50         return this.name.compareTo(other.getName());
    51     }
    52 
    53     public String toString() {
    54         return name + "	" + sex + "	" + age + "	" + id + "	" + birthplace + "
    ";
    55     }
    56 }
    

    实验结果

     

    实验十

    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    
    /*
     * 该程序用来随机生成0到100以内的加减乘除题
     */
    public class Demo {
        public static void main(String[] args) {
            // 用户的答案要从键盘输入,因此需要一个键盘输入流
            Scanner in = new Scanner(System.in);
            Counter counter = new Counter();
            PrintWriter out = null;
            try {
                out = new PrintWriter("text.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // 定义一个变量用来统计得分
            int sum = 0;
            int k = 0;
            // 通过循环生成10道题
            for (int i = 0; i < 10; i++) {
    
                // 随机生成两个100以内的随机数作加减乘除
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int d = (int) Math.round(Math.random() * 3);
    
                switch (d) {
    
                case 0:
                    if (a % b == 0) {
                        System.out.println(a + "/" + b + "=");
                        break;
                    }
                     int c = in.nextInt();
                     out.println(a + "/" + b + "="+c);
                case 1:
                    System.out.println(a + "*" + b + "=");
                     int c1 = in.nextInt();
                     out.println(a + "*" + b + "="+c1);
                    break;
                case 2:
                    System.out.println(a + "+" + b + "=");
                     int c2 = in.nextInt();
                     out.println(a + "+" + b + "="+c2);
                    break;
                case 3:
                    if (a > b) {
                        System.out.println(a + "-" + b + "=");
                        break;
                    }
                     int c3 = in.nextInt();
                   out.println(a + "-" + b + "="+c3);
    
                }
    
                // 定义一个整数用来接收用户输入的答案
                double c = in.nextDouble();
    
                // 判断用户输入的答案是否正确,正确给10分,错误不给分
                if (c == a / b | c == a * b | c == a + b | c == a - b) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                } else {
                    System.out.println("抱歉,答案错误");
    
                }
                out.println(a + "/" + b + "=" + c);
                out.println(a + "*" + b + "=" + c);
                out.println(a + "+" + b + "=" + c);
                out.println(a + "-" + b + "=" + c);
    
            }
            // 输出用户的成绩
            System.out.println("你的得分为" + sum);
    
            out.println("成绩:" + sum);
            out.close();
        }
    }
     1 public class Counter {
     2     private int a;
     3     private int b;
     4 
     5     public int add(int a, int b) {
     6         return a + b;
     7     }
     8 
     9     public int reduce(int a, int b) {
    10         return a - b;
    11     }
    12 
    13     public int multiplication(int a, int b) {
    14         return a * b;
    15     }
    16 
    17     public int division(int a, int b) {
    18         if (b != 0)
    19             return a / b;
    20         else
    21             return 0;
    22     }
    23 
    24 }

     小伙伴:狄慧

    通过结对实验,对互相存在的问题进行了解决,通过学习交流,对问题的看法有了不一样的切入点。结对编程,极大的提高了我们的编程兴趣,和编程效率,是一种很好的编程方式。通过学习交流,对问题的看法有了不一样的切入点。

    实验总结:

    1.Vector类类似长度可变的数组。Vector中只能存放对象。Vector的元素通过下标进行访问。 Vector类关键属性:capacity表示集合最多能容纳的元素个数。capacityIncrement表示每次增加多少容量。size表示集合当前元素个数。Stack类是Vector的子类。Stack类描述堆栈数据结构,即LIFO。Hashtable通过键来查找元素。Hashtable用散列码(hashcode)来确定键。所有对象都有一个散列码,可以通过Object类的hashCode()方法获得。

    2. ArrayList:可以将其看作是能够自动增长容量的数组。利用ArrayList的toArray()返回一个数组。Arrays.asList()返回一个列表。LinkedList是采用双向循环链表实现的。利用LinkedList实现栈(stack)、队列(queue)、双向队列 (double-ended queue )。ArrayList底层采用数组完成,而LinkedList则是以一般的双向链表(double-linked list)完成,其内每个对象除了数据本身外,还有两个引用,分别指向前一个元素和后一个元素。如果经常在 List 中进行插入和删除操作,应该使用LinkedList,否则,使用ArrayList将更加快速。

    3. TreeSet是一个有序集合,TreeSet中元素将按照升序排列,缺省是按照自然顺序进行排列,意味着TreeSet中元素要实现Comparable接口。可以在构造TreeSet对象时,传递实现了 Comparator接口的比较器对象。HashSet是基于Hash算法实现的,其性能通常都优于TreeSet。通常使用HashSet,需要排序的功能时,使用TreeSet。

    感受:

    本次实验不同于以往,采用结对编程,通过这种编程方式,对于有些个人能力限制及思考不到的问题,同伴之间的合作会产生更好的效果,在交流中不同的思维方式会产生不同角度的思考,并相互借鉴对方比较新颖的思路,对于解决问题更有效果。通过本周的学习我了解了新旧集合类的不同, 掌握了Vetor、StacHashtable三个类的用途, 对于HashSet类、TreeSet类的用途以及HashMap、TreeMap两个类的用途尚且理解不是很到位,在后面的学习中应该进行再理解。

  • 相关阅读:
    windows下面安装Python和pip教程
    Python已安装第三方库
    Python安装cx_Oracle第三方库(Mac osx Yosemite Intel i5环境)
    7.Python进阶_函数对象
    6.Python进阶_循环对象
    5.Python进阶_循环设计
    UltraEdit中粘贴问题
    UltraEdit的代码片的编码设置
    使用C#实现SSLSocket加密通讯 Https
    sql while 循环要加begin end
  • 原文地址:https://www.cnblogs.com/LRHLRH123----/p/9942140.html
Copyright © 2011-2022 走看看