201771010108 -韓臘梅-第十一週學習總結

第十一週總結java

1、知識總結編程

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能夠重複。dom

    HashMap (無序)
    TreeMap (有序)
    WeakHashMap
    Hashtable (無序,線程安全)
6.SortedSet和SortedMap接口對元素按指定規則排序,SortedMap是對key列進行排序。ide

7.ArrayList和Vector區別函數

   ArrayList和Vector都實現了List接口,都是經過數組實現的。
   ArrayList是非線程安全的, Vector是線程安全的。
   List第一次建立的時候,會有一個初始大小,隨着不斷向List中增長元素,當List 認爲容量不夠的時候就會進行擴容。ArrayList增加原來的50%,Vector缺省狀況下自動增加原來一倍的數組長度。
8.ArrayList和LinkedList區別及使用場景oop

區別:學習

 ArrayList底層是用數組實現的,能夠認爲ArrayList是一個可改變大小的數組, 查找速度快。隨着愈來愈多的元素被添加到ArrayList中,其大小是動態增長的。

  LinkedList底層是經過雙向鏈表實現的, LinkedList和ArrayList相比,增刪的速度較快。可是查詢和修改值的速度較慢。同時,LinkedList還實現了Queue接口,因此他還提供了offer(),peek(), poll()等方法。

使用場景:

ArrayList更適合快速檢索、以及在末尾插入或刪除(數組的特性)。
LinkedList更適合從中間插入或者刪除(鏈表的特性)。

2、實驗

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-三、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+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
    }
    
}

結果:

她的這個程序思路清晰,每一個步驟都很完善,運行屢次結果都如上所示

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+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
    }
    
}

結果:

採用結對編程方式,與學習夥伴合做完成實驗十編程練習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道題

3、實驗總結

        在本次實驗中我學習到了一個新的方法:結對編程。這個方法可讓同窗們互相討論,共同進步,對於學習語言來講是一個很是好的方法;而且在學習語言中要積極去閱讀好的源碼,這樣更有利於本身的學習。

相關文章
相關標籤/搜索