zoukankan      html  css  js  c++  java
  • 201771010124 王海珍 《面向对象设计java》第十一周总结

     

    第一部分  理论部分

      本章节的主要内容为集合

    (1)Java集合框架;

       a:将集合的接口与实现分离;

       b:Collection接口,集合类的基本接口。这个接口有两个基本方法

    public interface Collection<E>

    {

           boolean add (E element);

           Iterator<E> iterator();

    .....

    }

    c:迭送器;

    d:泛型使用方法,Collection与Iterator都是泛型接口;

    e:集合框架中的接口,集合有两个基本接口 Collection和Map;

    (2)具体的集合;

      a:链表,尽管数组在连续的存储位置上存放对象引用,但链表却将每个对象存放在独立的结点中。

      b:数组列表;

      c:散列表;散列表又称为哈希表。散列表算法的基本思想是:以结点的关键字为自变量,通过一定的函数关系(散列函数)算出对应的函数值,以这个值作为该结点存储在散列表的地址。

       散列表中的元素存放太满,就必须进行再散列,将产生一个新的散列表,所有元素存放到新的散列表中,原先的散列表将被删除。在Java语言中,通过负载因子(loadfactor)来决定何时对散列表进行再散列。例如:如果负载因子是0.75,当散列表中已经有75%的位置已经放满,那么将进行再散列。

      负载因子越高(越接近1.0),内存的使用效率越高,元素的寻找时间越长。负载因子越低(越接近0.0),元素的寻找时间越短,内存浪费越多。

      HashSet类的缺省负载因子是0.75。

     d: 队列和双端队列

    队列(Queue)是限定所有的插入只能在表的一端进行,而所有的删除都在表的另一端进行的线性表。

     表中允许插入的一端称为队尾(Rear),允许删除的一端称为队头(Front)。

     队列的操作是按先进先出(FIFO)的原则进行的。

     队列的物理存储可以用顺序存储结构,也可以用链式存储结构。

    (3)映射;

    a:基本映射操作;

    b:更新映射项;

    c:映射视图;

    d:弱散列映射;

    e:链接散列集与映射;

    f:枚举集与映射;

    (3)视图与包装器;

    a:轻量级集合包装器;

    b:子范图;

    c:不可修改的视图;

    d:同步视图;

    e:受查视图;

    f:关于可操作的说明;

    (4)算法;

    (5)遗留的集合。

    第二部分、实验目的与要求

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

    }

    }

    测试结果如下所示

     

     

    测试程序2:

    l 使用JDK命令编辑运行ArrayListDemo和LinkedListDemo两个程序,结合程序运行结果理解程序;

    import java.util.*;

    public class ArrayListDemo {

    public static void main(String[] argv) {

    ArrayList al = new ArrayList();

    // Add lots of elements to the ArrayList...

    al.add(new Integer(11));

    al.add(new Integer(12));

    al.add(new Integer(13));

    al.add(new String("hello"));

    // First print them out using a for loop.

    System.out.println("Retrieving by index:");

    for (int i = 0; i < al.size(); i++) {

    System.out.println("Element " + i + " = " + al.get(i));

    }

    }

    }

    import java.util.*;

    public class LinkedListDemo {

        public static void main(String[] argv) {

            LinkedList l = new LinkedList();

            l.add(new Object());

            l.add("Hello");

            l.add("zhangsan");

            ListIterator li = l.listIterator(0);

            while (li.hasNext())

                System.out.println(li.next());

            if (l.indexOf("Hello") < 0)   

                System.err.println("Lookup does not work");

            else

                System.err.println("Lookup works");

       }

    }

    测试结果如下所示

    l 在Elipse环境下编辑运行调试教材360页程序9-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<>();
    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       // merge the words from b into a
    26 
    27       ListIterator<String> aIter = a.listIterator();
    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 }
    

     

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

    测试程序3:

    l 运行SetDemo程序,结合运行结果理解程序;

    import java.util.*;

    public class SetDemo {

        public static void main(String[] argv) {

            HashSet h = new HashSet(); //也可以 Set h=new HashSet()

            h.add("One");

            h.add("Two");

            h.add("One"); // DUPLICATE

            h.add("Three");

            Iterator it = h.iterator();

            while (it.hasNext()) {

                 System.out.println(it.next());

            }

        }

    }

    测试结果如下所示

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

    package set;
    
    import java.util.*;
    
    /**
     * This program uses a set to print all unique words in System.in.
     * @version 1.12 2015-06-21
     * @author Cay Horstmann
     */
    public class SetTest
    {
       public static void main(String[] args)
       {
          Set<String> words = new HashSet<>(); // HashSet implements Set
          long totalTime = 0;
    
          try (Scanner in = new Scanner(System.in))
          {
             while (in.hasNext())
             {
                String word = in.next();
                long callTime = System.currentTimeMillis();
                words.add(word);
                callTime = System.currentTimeMillis() - callTime;
                totalTime += callTime;
             }
          }
    
          Iterator<String> iter = words.iterator();
          for (int i = 1; i <= 20 && iter.hasNext(); i++)
             System.out.println(iter.next());
          System.out.println(". . .");
          System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
       }
    }
    

     测试结果如下所示

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

    package treeSet;
    
    import java.util.*;
    
    /**
     * An item with a description and a part number.
     */
    public class Item implements Comparable<Item>
    {
       private String description;
       private int partNumber;
    
       /**
        * Constructs an item.
        * 
        * @param aDescription
        *           the item's description
        * @param aPartNumber
        *           the item's part number
        */
       public Item(String aDescription, int aPartNumber)
       {
          description = aDescription;
          partNumber = aPartNumber;
       }
    
       /**
        * Gets the description of this item.
        * 
        * @return the description
        */
       public String getDescription()
       {
          return description;
       }
    
       public String toString()
       {
          return "[description=" + description + ", partNumber=" + partNumber + "]";
       }
    
       public boolean equals(Object otherObject)
       {
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return Objects.equals(description, other.description) && partNumber == other.partNumber;
       }
    
       public int hashCode()
       {
          return Objects.hash(description, partNumber);
       }
    
       public int compareTo(Item other)
       {
          int diff = Integer.compare(partNumber, other.partNumber);
          return diff != 0 ? diff : description.compareTo(other.description);
       }
    }
    
    package treeSet;
    
    import java.util.*;
    
    /**
     * 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));
    
          sortByDescription.addAll(parts);
          System.out.println(sortByDescription);
       }
    }
    

     测试结果如下所示

    测试程序4:

    l 使用JDK命令运行HashMapDemo程序,结合程序运行结果理解程序;

    import java.util.*;

    public class HashMapDemo {

       public static void main(String[] argv) {

          HashMap h = new HashMap();

          // The hash maps from company name to address.

          h.put("Adobe", "Mountain View, CA");

          h.put("IBM", "White Plains, NY");

          h.put("Sun", "Mountain View, CA");

          String queryString = "Adobe";

          String resultString = (String)h.get(queryString);

          System.out.println("They are located in: " +  resultString);

      }

    }

    l 测试结果如下所示

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

    package map;
    
    /**
     * A minimalist employee class for testing purposes.
     */
    public class Employee
    {
       private String name;
       private double salary;
    
       /**
        * Constructs an employee with $0 salary.
        * @param n the employee name
        */
       public Employee(String name)
       {
          this.name = name;
          salary = 0;
       }
    
       public String toString()
       {
          return "[name=" + name + ", salary=" + salary + "]";
       }
    }
    
    package map;
    
    import java.util.*;
    
    /**
     * This program demonstrates the use of a map with key type String and value type Employee.
     * @version 1.12 2015-06-21
     * @author Cay Horstmann
     */
    public class MapTest
    {
       public static void main(String[] args)
       {
          Map<String, Employee> staff = new HashMap<>();
          staff.put("144-25-5464", new Employee("Amy Lee"));
          staff.put("567-24-2546", new Employee("Harry Hacker"));
          staff.put("157-62-7935", new Employee("Gary Cooper"));
          staff.put("456-62-5527", new Employee("Francesca Cruz"));
    
          // print all entries
    
          System.out.println(staff);
    
          // remove an entry
    
          staff.remove("567-24-2546");
    
          // replace an entry
    
          staff.put("456-62-5527", new Employee("Francesca Miller"));
    
          // look up a value
    
          System.out.println(staff.get("157-62-7935"));
    
          // iterate through all entries
    
          staff.forEach((k, v) -> 
             System.out.println("key=" + k + ", value=" + v));
       }
    }
    

     测试结果如下所示

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

    实验2:结对编程练习:

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

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

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

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

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

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

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

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

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

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

    采用结对编程方式,与学习伙伴合作完成实验九编程练习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 Test{
    
          private static ArrayList<Person> Personlist1;
           public static void main(String[] args) {
             
              Personlist1 = new ArrayList<>();
             
              Scanner scanner = new Scanner(System.in);
              File file = new File("C:\Users\lenovo\Documents\身份证");
       
                    try {
                         FileInputStream F = new FileInputStream(file);
                         BufferedReader in = new BufferedReader(new InputStreamReader(F));
                         String temp = null;
                         while ((temp = in.readLine()) != null) {
                            
                            Scanner linescanner = new Scanner(temp);
                            
                            linescanner.useDelimiter(" ");    
                            String name = linescanner.next();
                            String id = linescanner.next();
                            String sex = linescanner.next();
                            String age = linescanner.next();
                            String place =linescanner.nextLine();
                            Person Person = new Person();
                            Person.setname(name);
                            Person.setid(id);
                            Person.setsex(sex);
                            int a = Integer.parseInt(age);
                            Person.setage(a);
                            Person.setbirthplace(place);
                            Personlist1.add(Person);
    
                        }
                    } 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.输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地");
                        System.out.println("4:按省份找你的同乡;");
                        System.out.println("5:退出");
                        int type = scanner.nextInt();
                        switch (type) {
                        case 1:
                            Collections.sort(Personlist1);
                            System.out.println(Personlist1.toString());
                            break;
                        case 2:
                            
                            int max=0,min=100;int j,k1 = 0,k2=0;
                            for(int i=1;i<Personlist1.size();i++)
                            {
                                j=Personlist1.get(i).getage();
                               if(j>max)
                               {
                                   max=j; 
                                   k1=i;
                               }
                               if(j<min)
                               {
                                   min=j; 
                                   k2=i;
                               }
    
                            }  
                            System.out.println("年龄最大:"+Personlist1.get(k1));
                            System.out.println("年龄最小:"+Personlist1.get(k2));
                            break;
                        case 3:
                            System.out.println("place?");
                            String find = scanner.next();        
                            String place=find.substring(0,3);
                            String place2=find.substring(0,3);
                            for (int i = 0; i <Personlist1.size(); i++) 
                            {
                                if(Personlist1.get(i).getbirthplace().substring(1,4).equals(place)) 
                                {
                                    System.out.println("你的同乡:"+Personlist1.get(i));
                                }
                            } 
    
                            break;
                        case 4:
                            System.out.println("年龄:");
                            int yourage = scanner.nextInt();
                            int close=ageclose(yourage);
                            int d_value=yourage-Personlist1.get(close).getage();
                            System.out.println(""+Personlist1.get(close));
                      
                            break;
                        case 5:
                       isTrue = false;
                       System.out.println("再见!");
                            break;
                        default:
                            System.out.println("输入有误");
                        }
                    }
                }
                public static int ageclose(int age) {
                       int m=0;
                    int    max=53;
                    int d_value=0;
                    int k=0;
                    for (int i = 0; i < Personlist1.size(); i++)
                    {
                        d_value=Personlist1.get(i).getage()-age;
                        if(d_value<0) d_value=-d_value; 
                        if (d_value<max) 
                        {
                           max=d_value;
                           k=i;
                        }
    
                     }    return k;
                    
                 }
    }
    
    public class Person implements Comparable<Person> {
                private String name;
                private String id;
                private int age;
                private String sex;
                private String birthplace;
    
        public String getname() {
            return name;
            }
        public void setname(String name) {
            this.name = name;
        }
        public String getid() {
            return id;
        }
        public void setid(String id) {
            this.id= id;
        }
        public int getage() {
        
            return age;
        }
        public void setage(int age) {
            // int a = Integer.parseInt(age);
            this.age= age;
        }
        public String getsex() {
            return sex;
        }
        public void setsex(String sex) {
            this.sex= sex;
        }
        public String getbirthplace() {
            return birthplace;
        }
        public void setbirthplace(String birthplace) {
            this.birthplace= birthplace;
    }
    
        public int compareTo(Person o) {
            return this.name.compareTo(o.getname());
    
    }
    
        public String toString() {
            return  name+"	"+sex+"	"+age+"	"+id+"	";
    
    }
    }
    

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

    package Demo;
    
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Random;
    import java.util.Scanner;
    
    public class Demo {
        public static void main(String[] args) {
    
            Scanner in = new Scanner(System.in);
            Number counter = new Number();
            PrintWriter out = null;
            try {
                out = new PrintWriter("test.txt");
            } catch (FileNotFoundException e) {
                System.out.println("Error!");
                e.printStackTrace();
            }
    
            int sum = 0;
          
    
            for (int i = 1; i <= 10; i++) {
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int m;
                Random rand = new Random();
                m = (int) rand.nextInt(4) + 1;
    
    
                switch (m) {
                case 1:
                    a = b + (int) Math.round(Math.random() * 100);
                    while(b == 0){
                        b = (int) Math.round(Math.random() * 100);
                    }
                    while(a % b != 0){
                        a = (int) Math.round(Math.random() * 100);
                        
                    }
                    //a大于b,a%b为0(保证能整除)
                    System.out.println(i + ": " + a + "/" + b + "=");
    
                    int c0 = in.nextInt();
                    out.println(a + "/" + b + "=" + c0);
                    if (c0 == counter.division(a, b)) {
                        sum += 10;
                        System.out.println("恭喜答案正确!");
                    } else {
                        System.out.println("抱歉答案错误!");
                    }
    
                    break;
    
                case 2:
                    System.out.println(i + ": " + a + "*" + b + "=");
                    int c = in.nextInt();
                    out.println(a + "*" + b + "=" + c);
                    if (c == counter.multiplication(a, b)) {
                        sum += 10;
                        System.out.println("恭喜答案正确!");
                    } else {
                        System.out.println("抱歉答案错误!");
                    }
                    break;
                case 3:
                    System.out.println(i + ": " + a + "+" + b + "=");
                    int c1 = in.nextInt();
                    out.println(a + "+" + b + "=" + c1);
                    if (c1 == counter.add(a, b)) {
                        sum += 10;
                        System.out.println("恭喜答案正确!");
                    } else {
                        System.out.println("抱歉答案错误!");
                    }
                    break;
                case 4:
                    while (a < b) {
                        b = (int) Math.round(Math.random() * 100);
                    }
                     //若a<b,则重新生成b(避免出现负数)
                    System.out.println(i + ": " + a + "-" + b + "=");
                    int c2 = in.nextInt();
                    out.println(a + "-" + b + "=" + c2);
                    if (c2 == counter.reduce(a, b)) {
                        sum += 10;
                        System.out.println("恭喜答案正确!");
                    } else {
                        System.out.println("抱歉答案错误!");
                    }
                    break;
                }
            }
            System.out.println("成绩" + sum);
            out.println("成绩:" + sum);
            out.close();
        }
    }
    
    package Demo;
    
    public class Number<T> {
        private T a;
        private T b;
    
        public Number() {
            a = null;
            b = null;
        }
        public Number(T a, T b) {
            this.a = a;
            this.b = b;
        }
              
        public int add(int a,int b) {
            return a + b;
        }
    
        public int reduce(int a, int b) {
            return a - b;
        }
    
        public int multiplication(int a, int b) {
            return a * b;
        }
    
        public int division(int a, int b) {
            if (b != 0 && a%b==0)
                return a / b;
            else
                return 0;
        }
    }
    

     

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

    package xinxi;
    
    
    
    public class Student implements Comparable<Student> {
    
        private String name;
        private String number ;
        private String sex ;
        private int age;
        private String province;
       
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getnumber() {
            return number;
        }
        public void setnumber(String number) {
            this.number = number;
        }
        public String getsex() {
            return sex ;
        }
        public void setsex(String sex ) {
            this.sex =sex ;
        }
        public int getage() {
    
            return age;
            }
        public void setage(int age) {
            this.age= age;
            }
    
        public String getprovince() {
            return province;
        }
        public void setprovince(String province) {
            this.province=province ;
        }
    
        public int compareTo(Student o) {
           return this.name.compareTo(o.getName());
        }
    
        public String toString() {
            return  name+"	"+sex+"	"+age+"	"+number+"	"+province+"
    ";
        }    
    }
    
    package xinxi;
    
    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 xinxi{
        private static ArrayList<Student> studentlist;
        public static void main(String[] args) {
            studentlist = new ArrayList<>();
            @SuppressWarnings("resource")
            Scanner scanner = new Scanner(System.in);
            File file = new File("F:\身份证号.txt");
            try {
                FileInputStream fis = new FileInputStream(file);
                @SuppressWarnings("resource")
                BufferedReader in = new BufferedReader(new InputStreamReader(fis));
                String temp = null;
                while ((temp = in.readLine()) != null) {
                    
                    @SuppressWarnings("resource")
                    Scanner linescanner = new Scanner(temp);
                    
                    linescanner.useDelimiter(" ");    
                    String name = linescanner.next();
                    String number = linescanner.next();
                    String sex = linescanner.next();
                    String age = linescanner.next();
                    String province =linescanner.nextLine();
                    Student student = new Student();
                    student.setName(name);
                    student.setnumber(number);
                    student.setsex(sex);
                    int a = Integer.parseInt(age);
                    student.setage(a);
                    student.setprovince(province);
                    studentlist.add(student);
    
                }
            } catch (FileNotFoundException e) {
                System.out.println("学生信息文件找不到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("学生信息文件读取错误");
                e.printStackTrace();
            }
            boolean isTrue = true;
            while (isTrue) {
                System.out.println("输入序号进行相应的操作");
                System.out.println("1.字典排序");
                System.out.println("2.输出年龄最大和年龄最小的人");
                System.out.println("3.查找与你年龄相近的人");
                System.out.println("4.查找你的同乡");
                String n = scanner.next();
                switch (n) {
                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("年龄:");
                    int yourage = scanner.nextInt();
                    int near=agenear(yourage);
                    @SuppressWarnings("unused") int value=yourage-studentlist.get(near).getage();
                    System.out.println("和你年龄相近的是"+studentlist.get(near));
                    break;
    
                case "4":
                     System.out.println("输入你的家乡");
                     String find = scanner.next();        
                     String place=find.substring(0,3);
                     for (int i = 0; i <studentlist.size(); i++) 
                     {
                         if(studentlist.get(i).getprovince().substring(1,4).equals(place)) 
                             System.out.println("你的同乡是  "+studentlist.get(i));
                     }             
                     break;
    
                }
            }
        }
            public static int agenear(int age) {      
            @SuppressWarnings("unused")
            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;         
          
    
    }
    
    
    }
    

     

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

    package jisuan;
    
    import java.io.*;
    import java.io.PrintWriter;
    import java.util.Scanner;
    
    public class Jisuan {
        public static void main(String[] args) {
    
            Scanner in = new Scanner(System.in);
    
            PrintWriter output = null;
            try {
                output = new PrintWriter("text.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int sum = 0;
            for (int i = 1; i <= 10; i++) {
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int m = (int) Math.round(Math.random() * 4);
                switch (m) {
                case 1:
                    while (b == 0) {
                        b = (int) Math.round(Math.random() * 100);
                    }
                    while (a % b != 0) {
                        a = (int) Math.round(Math.random() * 100);
                    }
                    System.out.println(a + "/" + b + "=");
                    int c1 = in.nextInt();
                    output.println(a + "/" + b + "=" + c1);
                    if (c1 == a / b) {
                        System.out.println("恭喜答案正确");
                        sum += 10;
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
    
                    break;
    
                case 2:
                    System.out.println( a + "*" + b + "=");
                    int c2 = in.nextInt();
                    output.println(a + "*" + b + "=" + c2);
                    if (c2 == a * b) {
                        System.out.println("恭喜答案正确");
                        sum += 10;
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
                    break;
                case 3:
                    System.out.println( a + "+" + b + "=");
                    int c3 = in.nextInt();
                    output.println(a + "+" + b + "=" + c3);
                    if (c3 == a + b) {
                        System.out.println("恭喜答案正确");
                        sum += 10;
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
    
                    break;
                case 4:
                    while (a < b) {
                        a = (int) Math.round(Math.random() * 100);
                    }
                    System.out.println( a + "-" + b + "=");
                    int c4 = in.nextInt();
                    output.println(a + "-" + b + "=" + c4);
                    if (c4 == a - b) {
                        System.out.println("恭喜答案正确");
                        sum += 10;
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
                    break;
    
                }
    
            }
            System.out.println("成绩" + sum);
            output.println("成绩" + sum);
            output.close();
        }
    }
    
    package jisuan;
    public class math<T> {
        private T a;
        private T b;
    
        public int add(int a, int b) {
            return a + b;
        }
    
        public int reduce(int a, int b) {
            return a - b;
        }
    
        public int multiplication(int a, int b) {
            return a * b;
        }
    
        public int division(int a, int b) {
            if (b != 0 && a % b == 0)
                return a / b;
            else
                return 0;
        }
    }
    

     

    实验总结

          本次实验主要分为自主完成部分和合作完成部分,这是java作业的第一次结对作业,相比来说还是有很大的收获的,通过两个人进行分工和合作部分一起完成作业,而且过程非常顺利。期待下次合作。

  • 相关阅读:
    sql知识点记录
    makefile编译错误情况整理
    web worker 简介
    实现跨域访问的方法总结
    fiddler使用指南
    [转]SASS用法指南
    koa文档参考
    [转]html5: postMessage解决跨域和跨页面通信的问题
    [转]JavaScript ES6 class指南
    [转]前端利器:SASS基础与Compass入门
  • 原文地址:https://www.cnblogs.com/www-whz-1997/p/9931815.html
Copyright © 2011-2022 走看看