zoukankan      html  css  js  c++  java
  • 达拉草201771010105《面向对象程序设计(java)》第十一周学习总结

    达拉草201771010105《面向对象程序设计(java)》第十一周学习总结

    实验十一   集合

    实验时间 2018-11-8

    第一部分:理论知识

    1.集合(Collection或称为容器)是一种包含多个元素 并提供对所包含元素操作方法的类,其包含的元 素可以由同一类型的对象组成,也可以由不同类 型的对象组成。 

    2.集合框架:JAVA集合类库的统一架构。

    集合类的作用: –Java的集合类提供了一些基本数据结构的支持。 例如Vector、Hashtable、Stack等。

    集合类的使用: –Java的集合类包含在java.util包中。

    集合类的特点:

    特点一: 只容纳对象。 注意:数组可以容纳基本数据类型数据和对象。 –如果集合类中想使用基本数据类型,又想利用 集合类的灵活性,可以把基本数据类型数据封 装成该数据类型的包装器对象,然后放入集合 中处理。

    特点二: 集合类容纳的对象都是Object类的实例,一旦 把一个对象置入集合类中,它的类信息将丢失 ,这样设计的目的是为了集合类的通用性。 因为Object类是所有类的祖先,所以可以在这 些集合中存放任何类的对象而不受限制,但切 记在使用集合成员之前必须对它重新造型。

    Vector类:

    Vector类类似长度可变的数组。

    Vector中只能存放对象。

    Vector的元素通过下标进行访问。

    Vector类关键属性: capacity表示集合多能容纳的元素个数。 capacityIncrement表示每次增加多少容量。 size表示集合当前元素个数。

    Stack类:Stack类是Vector的子类。 

    Hashtable类:
    Hashtable通过键来查找元素。
    Hashtable用散列码(hashcode)来确定键。所 有对象都有一个散列码,可以通过Object类的 hashCode()方法获得。

    Math.random()方法的随机性。在理想 情况下,该方法应该产生一系列完美的随机分布的 数字。为了验证这一点,需要生成数量众多的随机 数字,然后计算落在不同范围内的数字量。该程序 生成10000个随机数,查看它们在0~20之间的分 布如何。 Math.random()
    返回带正号的double值,大于或等于0.0,小于1.0。

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

    Set:不能包含重复的元素。对象可能不是按存放的 次序存放,也就是说不能像数组一样按索引的方式进 行访问,SortedSet是一个按照升序排列元素的Set。

    List:是一个有序的集合,可以包含重复的元素。提 供了按索引访问的方式。 Map:包含了key-value对。Map不能包含重复的key 。

    SortedMap是一个按照升序排列key的Map。

    List:
    List的明显特征是它的元素 都有一个确定的顺序。

    实现它的类有ArrayList和 LinkedList。 –ArrayList中的元素在内存中 是顺序存储的。

    LinkedList中的元素在内存 中是以链表方式存储的。 List的明显特征是它的元素 都有一个确定的顺序。

    实现它的类有ArrayList和 LinkedList。

    ArrayList中的元素在内存中 是顺序存储的。

    LinkedList中的元素在内存 中是以链表方式存储的。

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

    }

    }

    示例程序一:

     1 import java.util.Vector;
     2 
     3 class Cat {
     4     private int catNumber;
     5 
     6     Cat(int i) {
     7         catNumber = i;
     8     }
     9 
    10     void print() {
    11         System.out.println("Cat #" + catNumber);
    12     }
    13 }
    14 
    15 class Dog {
    16     private int dogNumber;
    17 
    18     Dog(int i) {
    19         dogNumber = i;
    20     }
    21 
    22     void print() {
    23         System.out.println("Dog #" + dogNumber);
    24     }
    25 }
    26 
    27 public class CatsAndDogs {
    28     public static void main(String[] args) {
    29         Vector cats = new Vector();
    30         for (int i = 0; i < 7; i++)
    31             cats.addElement(new Cat(i));
    32         cats.addElement(new Dog(7));
    33         for (int i = 0; i < cats.size(); i++)
    34             ((Cat) cats.elementAt(i)).print();//进行强制类型转换
    35     }
    36 }

    程序运行结果如下

    出现这个是由于dog类无法强制类型转换为cat类 

    修改之后的程序如下:

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

    运行结果如下:

     示例程序二:

     1 import java.util.*;
     2 
     3 public class Stacks {
     4     static String[] months = { "1", "2", "3", "4" };
     5 
     6     public static void main(String[] args) {
     7         Stack stk = new Stack();
     8         for (int i = 0; i < months.length; i++)
     9             stk.push(months[i]);//进栈
    10         System.out.println(stk);
    11         System.out.println("element 2=" + stk.elementAt(2));
    12         while (!stk.empty())
    13             System.out.println(stk.pop());//出栈
    14     }
    15 }

    程序运行结果如下:

    示例程序三:

     1 import java.util.*;
     2 
     3 class Counter {
     4 
     5 int i = 1;
     6 
     7 public String toString()//把其他类型的数据转化为字符串类型的
     8 
     9 {
    10 
    11 return Integer.toString(i);
    12 
    13 }
    14 
    15 }
    16 
    17 public class Statistics {
    18 
    19 public static void main(String[] args) {
    20 
    21 Hashtable ht = new Hashtable();
    22 
    23 for (int i = 0; i < 10000; i++) {
    24 
    25 Integer r = new Integer((int) (Math.random() * 20));//生成0~1之间的随机数
    26 
    27 if (ht.containsKey(r))
    28 
    29 ((Counter) ht.get(r)).i++;
    30 
    31 else
    32 
    33 ht.put(r, new Counter());
    34 
    35 }
    36 
    37 System.out.println(ht);
    38 
    39 }
    40 
    41 }

    运行结果如下:

    测试程序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");

       }

    }

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

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

    1.运行ArrayListDemo:

     1 import java.util.*;
     2 
     3 public class ArrayListDemo {
     4     public static void main(String[] argv) {
     5         ArrayList al = new ArrayList();//a1调用ArrayList类数组
     6 
     7 
     8         //向ArrayList中添加大量元素
     9         al.add(new Integer(11));
    10         al.add(new Integer(12));
    11         al.add(new Integer(13));
    12         al.add(new String("hello"));
    13         // 首先用一个for循环打印出来。
    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 }

    运行结果如下:

    2.运行LinkedListDemo

     1 import java.util.*;
     2 public class LinkedListDemo {
     3     public static void main(String[] argv) {
     4         LinkedList l = new LinkedList();
     5         l.add(new Object());
     6         l.add("Hello");
     7         l.add("zhangsan");
     8         ListIterator li = l.listIterator(0);
     9         while (li.hasNext())
    10             System.out.println(li.next());
    11         if (l.indexOf("Hello") < 0)   
    12             System.err.println("Lookup does not work");
    13         else
    14             System.err.println("Lookup works");
    15    }
    16 }

    运行结果如下:

    3.运行调试教材360页程序9-1

     1 package linkedList;
     2 
     3 import java.util.*;
     4 
     5 /**
     6  * This program demonstrates operations on linked lists.
     7  * @version 1.11 2012-01-26
     8  * @author Cay Horstmann
     9  */
    10 public class LinkedListTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       List<String> a = new LinkedList<>();//创建一个泛型类,用a引用它
    15       a.add("Amy");
    16       a.add("Carl");
    17       a.add("Erica");
    18 
    19       List<String> b = new LinkedList<>();
    20       b.add("Bob");
    21       b.add("Doug");
    22       b.add("Frances");
    23       b.add("Gloria");
    24 
    25       // 将a和b合并起来
    26 
    27       ListIterator<String> aIter = a.listIterator();//遍历a中的所有元素,且a中元素为string类
    28       Iterator<String> bIter = b.iterator();
    29 
    30       while (bIter.hasNext())
    31       {
    32          if (aIter.hasNext()) aIter.next();
    33          aIter.add(bIter.next());
    34       }
    35 
    36       System.out.println(a);
    37 
    38       // remove every second word from b
    39 
    40       bIter = b.iterator();
    41       while (bIter.hasNext())
    42       {
    43          bIter.next(); // skip one element
    44          if (bIter.hasNext())
    45          {
    46             bIter.next(); // skip next element
    47             bIter.remove(); // remove that element
    48          }
    49       }
    50 
    51       System.out.println(b);
    52 
    53       // bulk operation: remove all words in b from a
    54 
    55       a.removeAll(b);
    56 
    57       System.out.println(a);
    58    }
    59 }

    运行结果如下;

     总结:

    1.LinkedList类实现了List接口,允许null元素。此外LinkedList提供额外的get,remove,insert方法在 LinkedList的首部或尾部。

    2.ArrayList实现了可变大小的数组。

    3.ArrayList方便查询,占用空间小。LinkedList方便添加删除等修改操作,占用空间大。

    测试程序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());

            }

        }

    }

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

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

     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"); // DUPLICATE
     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  * @version 1.12 2015-06-21
     8  * @author Cay Horstmann
     9  */
    10 public class SetTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       Set<String> words = new HashSet<>(); // HashSet implements Set
    15       long totalTime = 0;
    16 
    17       try (Scanner in = new Scanner(System.in))
    18       {
    19          while (in.hasNext())
    20          {
    21             String word = in.next();
    22             long callTime = System.currentTimeMillis();
    23             words.add(word);
    24             callTime = System.currentTimeMillis() - callTime;
    25             totalTime += callTime;
    26          }
    27       }
    28 
    29       Iterator<String> iter = words.iterator();
    30       for (int i = 1; i <= 20 && iter.hasNext(); i++)
    31          System.out.println(iter.next());
    32       System.out.println(". . .");
    33       System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
    34    }
    35 }

    在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<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:

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

      }

    }

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

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

    1.运行HashMapDemo程序,结合程序运行结果理解程序;

    package treeSet;
    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";//访问指定的关键字Adobe
    
          String resultString = (String)h.get(queryString);
          System.out.println("They are located in: " +  resultString);
      }
    }

    运行结果如下:

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

    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:结对编程练习:

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

     

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

    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,结合使用体验对所运行程序提出完善建议;

    package gbfdb;
    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 gbfdb;
    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 gbfdb;
    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 gbfdb;
    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;

    package gbfdb;
    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 Moom{
        private static ArrayList<Mest> 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();
                    Mest student = new Mest();
                    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("家庭住址:");
                     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 gbfdb;
    public  class Mest implements Comparable<Mest> {
    
        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(Mest o) {
           return this.name.compareTo(o.getName());
        }
    
        public String toString() {
            return  name+"	"+sex+"	"+age+"	"+number+"	"+province+"
    ";
        }
        
    }

    运行结果如下:

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

    package gbfdb;
    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 gbfdb;
    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;
       }
       }

    运行结果如下:

    实验总结:

     这周我们通过一种新的学习方式结对编程进行这周的编程实验,我觉得结对编程可以让我们交流我们的思路,然后可以发现我们自己的不足。这周我们学习了集合,掌握了java中集合的概念,学习了集合的知识以及使用方法。

  • 相关阅读:
    利用相关的Aware接口
    java 值传递和引用传递。
    权限控制框架Spring Security 和Shiro 的总结
    优秀代码养成
    Servlet 基础知识
    leetcode 501. Find Mode in Binary Search Tree
    leetcode 530. Minimum Absolute Difference in BST
    leetcode 543. Diameter of Binary Tree
    leetcode 551. Student Attendance Record I
    leetcode 563. Binary Tree Tilt
  • 原文地址:https://www.cnblogs.com/dalacao/p/9930623.html
Copyright © 2011-2022 走看看