201771010108 -韩腊梅-第十一周学习总结

第十一周总结

一、知识总结

1.Collection和Map是Java集合框架的根接口。

2.List接口和Set接口继承自Collection接口。
3.Set无序不允许元素重复。

    HashSet (无序)
    TreeSet (有序)
4.List有序且允许元素重复。

    ArrayList
    LinkedList
    Vector
5.Map也属于集合系统,但和Collection接口没关系。Map是key对value的映射集合,其中key列就是一个集合。key不能重复,但是value可以重复。

    HashMap (无序)
    TreeMap (有序)
    WeakHashMap
    Hashtable (无序,线程安全)
6.SortedSet和SortedMap接口对元素按指定规则排序,SortedMap是对key列进行排序。

7.ArrayList和Vector区别

   ArrayList和Vector都实现了List接口,都是通过数组实现的。
   ArrayList是非线程安全的, Vector是线程安全的。
   List第一次创建的时候,会有一个初始大小,随着不断向List中增加元素,当List 认为容量不够的时候就会进行扩容。ArrayList增长原来的50%,Vector缺省情况下自动增长原来一倍的数组长度。
8.ArrayList和LinkedList区别及使用场景

区别:

 ArrayList底层是用数组实现的,可以认为ArrayList是一个可改变大小的数组, 查找速度快。随着越来越多的元素被添加到ArrayList中,其大小是动态增加的。

  LinkedList底层是通过双向链表实现的, LinkedList和ArrayList相比,增删的速度较快。但是查询和修改值的速度较慢。同时,LinkedList还实现了Queue接口,所以他还提供了offer(),peek(), poll()等方法。

使用场景:

ArrayList更适合快速检索、以及在末尾插入或删除(数组的特性)。
LinkedList更适合从中间插入或者删除(链表的特性)。

二、实验

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:

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

掌握Vetor、Stack、Hashtable三个类的用途及常用API。

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();//进行强制类型转化
    }
}
示例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++)
            if (cats.elementAt(i) instanceof Cat) //判断是否能进行强制类型转换
            {
                ((Cat) cats.elementAt(i)).print();//能进行强制类型转换,输出为Cat型
            } else {
                ((Dog) cats.elementAt(i)).print();//不能进行强制类型转化,输出为Dog型
            }
    }
}
示例一(改正)

改后结果为:

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());//出栈操作,并输出
    }
}
示例2

结果:

import java.util.*;

class Counter {
int i = 1;//i不加权限修饰符,所以i的缺省权限修饰符应该是friendly型

public String toString() //转为字符串类型的数据
{
return Integer.toString(i);
}
}

public class Statistics {
public static void main(String[] args) {
Hashtable ht = new Hashtable();//Hashtable保存集合数据,用键值对的方式保存集合数据
for (int i = 0; i < 10000; i++) {
Integer r = new Integer((int) (Math.random() * 20));//生成0到19,即20个整型随机数
if (ht.containsKey(r))//判断r是否是哈希表中一个元素的键值
((Counter) ht.get(r)).i++;//利用Counter类对象去引用属性值
else
ht.put(r, new Counter());//r是随机数,新创建的Counter对象的初始值是1
}
System.out.println(ht);
}
}
示例3

结果:

测试程序2:

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

import java.util.*;

public class ArrayListDemo//ArrayList使用了数组的实现
{
    public static void main(String[] argv) {
        ArrayList al = new ArrayList();
        //在ArrayList中添加大量元素
        al.add(new Integer(11));
        al.add(new Integer(12));
        al.add(new Integer(13));
        al.add(new String("hello"));//下标从0开始,添加4个元素
        // 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));//通过get方法找到
        }
    }
}
ArrayListDemo

结果:

添加一个输出一个集合对象的结果:

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");
   }
}
LinkedListDemo

结果:

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

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

import java.util.*;

/**
 * This program demonstrates operations on linked lists.
 * @version 1.11 2012-01-26
 * @author Cay Horstmann
 */
public class LinkedListTest
{
   public static void main(String[] args)
   {
       //创建a和b两个链表
      List<String> a = new LinkedList<>();
      a.add("Amy");
      a.add("Carl");
      a.add("Erica");

      List<String> b = new LinkedList<>();
      b.add("Bob");
      b.add("Doug");
      b.add("Frances");
      b.add("Gloria");

      //合并a和b中的词

      ListIterator<String> aIter = a.listIterator();
      Iterator<String> bIter = b.iterator();

      while (bIter.hasNext())
      {
         if (aIter.hasNext()) aIter.next();
         aIter.add(bIter.next());
      }

      System.out.println(a);

      //从第二个链表中每隔一个元素删除一个元素

      bIter = b.iterator();
      while (bIter.hasNext())
      {
         bIter.next(); // skip one element
         if (bIter.hasNext())
         {
            bIter.next(); // skip next element
            bIter.remove(); // remove that element
         }
      }

      System.out.println(b);

      // bulk operation: remove all words in b from a

      a.removeAll(b);

      System.out.println(a);//通过toString方法打印出链表a中的所有元素
   }
}
9-1

测试程序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"); // 复制
        h.add("Three");
        Iterator it = h.iterator();
        while (it.hasNext()) {
             System.out.println(it.next());
        }
    }
}
SetDemo

结果:

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

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

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.");
   }
}
9-2
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);
   }
}
9-3
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);
   }
}
9-4

结果:

测试程序4:

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

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

结果:

了解HashMap、TreeMap两个类的用途及常用API。在Elipse环境下调试教材373页程序9-6,结合程序运行结果理解程序;

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));
   }
}
9-6

结果:

实验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 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;         
      }

}
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+"
";
    }
    
}

结果:

她的这个程序思路清晰,每个步骤都很完善,运行多次结果都如上所示

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

package MM;
   
  import java.util.Random;
  import java.util.Scanner;
  
  import java.io.FileNotFoundException;
  
  import java.io.PrintWriter;
  
  public class Demo{
     public static void main(String[] args)
  {
     
         MNM counter=new MNM();//与其它类建立联系
     PrintWriter out=null;
    try {
         out=new PrintWriter("D:/text.txt");
         
    }catch(FileNotFoundException e) 
    {       
         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 M = in.nextInt();
          System.out.println(a+"+"+b+"="+M);
          if (M == counter.add(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 N= in.nextInt();
        
         System.out.println(a+"-"+b+"="+N);
          if (N == counter.reduce(a, b)) 
          {
             sum += 10;
            System.out.println("答案正确");
         }
          else {
             System.out.println("答案错误");
        }
           
          break ;
     
      
     case 2:
         System.out.println(""+a+"*"+b+"=");
         int c = in.nextInt();
        System.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+"=");
          while(b==0)
          {  b = (int) Math.round(Math.random() * 100);
          }
      int c0= in.nextInt();
      System.out.println(a+"/"+b+"="+c0);
      if (c0 == counter.devision(a, b)) {
          sum += 10;
          System.out.println("答案正确");
      }
     else {
          System.out.println("答案错误");
      }
     
     break;
      
 
     }
     }
     System.out.println("totlescore:"+sum);
     System.out.println(sum);
    
     out.close();
    }
     }
package MM;
  
  public class MNM <T>{
      private T a;
      private T b;
      public void MNM()
      {
          a=null;
          b=null;
      }
      public MNM(T a,T b) 
      {
          this.a=a;
          this.b=b;
      }
      public MNM() {
        // TODO 自动生成的构造函数存根
    }
    public int add(int a,int b)
      {
          return a+b;
      }
      public int reduce(int a,int b)
      {
         if((a-b)>0)
         return a-b;
         else return 0;
     }
     public int multiply(int a,int b)
     {
         return a*b;
     }
    public int devision(int a,int b)
     {
         if(b!=0&&a%b==0)
         return  a/b;
         else 
             return 0;
         
    }
    }

结果:

在运行这个程序时,大概出了5道题之后不出来其他题了,问题大概是我在输入答案之前先按了回车键,在进行第二次操作时,一切正常

出错情况如下:

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

public class A{
    private static ArrayList<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;         
      }

}
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。

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

结果:

按回车键依旧输出10道题

三、实验总结

        在本次实验中我学习到了一个新的方法:结对编程。这个方法可以让同学们互相讨论,共同进步,对于学习语言来说是一个非常好的方法;并且在学习语言中要积极去阅读好的源码,这样更有利于自己的学习。

原文地址:https://www.cnblogs.com/hanlamei/p/9941906.html