1. 程式人生 > >馬凱軍201771010116《面向物件與程式設計Java》第十一週學習總結

馬凱軍201771010116《面向物件與程式設計Java》第十一週學習總結

一.理論知識部分

第九章  集合

1.資料結構介紹:線性結構:線性表,棧,佇列,串,陣列,檔案。非線性結構:樹,圖。

散列表:又稱為雜湊表。

散列表演算法的基本思想是:以結點的關鍵字為自變數,通過一定的函式關係(雜湊函式)計算出對應的函式值,以這個值作為該結點儲存在散列表中的地址。當散列表中的元素存放太滿,就必須進行再雜湊,將產生一個新的散列表,所有元素存放到新的散列表中,原先的散列表將被刪除。

2.java的集合框架:

JAVA的集合框架實現對各種資料結構的封裝,以降低對資料管理與處理的難度。所謂框架就是一個類庫的集合,框架中包含很多超類,程式設計者建立這些超類的子類可較方便的設計程式所需的類。集合(Collection或稱為容器)是一種包含多個元素並提供對所包含元素操作方法的類,其包含的元素可以由同一型別的物件組成,也可以由不同型別的物件組成。

3.集合框架:JAVA集合類庫的統一架構。

4.集合類的作用:Java的集合類提供了一些基本資料結構的支援。例如Vector、Hashtable、Stack等。

5.集合類的使用:Java的集合類包含在java.util包中。

6.集合類的特點:

特點一:只容納物件。

注意:陣列可以容納基本資料型別資料和物件。如果集合類中想使用基本資料型別,又想利用集合類的靈活性,可以把基本資料型別資料封裝成該資料型別的包裝器物件,然後放入集中處理。

特點二:集合類容納的物件都是Object類的例項,一旦把一個物件置入集合類中,它的類資訊將丟失,這樣設計的目的是為了集合類的通用性。因為Object類是所有類的祖先,所以可以在這些集合中存放任何類的物件而不受限制,但切記在使用集合成員之前必須對它重新造型。

7.DK1.1版本中的集合類:Vector、Stack、Hashtable

<1>Vector類類似長度可變的陣列。Vector中只能存放物件。Vector的元素通過下標進行訪問。

Vector類關鍵屬性:(1)capacity表示集合最多能容納的元素個數。(2)capacityIncrement表示每次增加多少容量。(3)size表示集合當前元素個數。 

<2>Stack類是Vector的子類。Stack類描述堆疊資料結構,即LIFO。

<3>Hashtable通過鍵來查詢元素。Hashtable用雜湊碼(hashcode)來確定鍵。所有物件都有一個雜湊碼,可以通過Object類的hashCode()方法獲得。

8.集合框架中的基本介面:

(1)Collection:集合層次中的根介面,JDK未提供這個介面的直接實現類。

(2)Set:不能包含重複的元素。物件可能不是按存放的次序存放,也就是說不能像陣列一樣按索引的方式進行訪問,SortedSet是一個按照升序排列元素的Set。

(3)List:是一個有序的集合,可以包含重複的元素。提供了按索引訪問的方式。

(4)Map:包含了key-value對。Map不能包含重複的key。

(5)SortedMap是一個按照升序排列key的Map。

9.ArrayList:可以將其看作是能夠自動增長容量的陣列。利用ArrayList的toArray()返回一個數組。Arrays.asList()返回一個列表。

10.LinkedList是採用雙向迴圈連結串列實現的。利用LinkedList實現棧(stack)、佇列(queue)、雙向佇列(double-endedqueue)。ArrayList底層採用陣列完成,而LinkedList則是以一般的雙向連結串列(double-linkedlist)完成,其內每個物件除了資料本身外,還有兩個引用,分別指向前一個元素和後一個元素。

11.如果經常在List中進行插入和刪除操作,應該使用LinkedList,否則,使用ArrayList將更加快速。

12.Set中的元素必須唯一。新增到Set中的物件元素必須定義equals方法,以提供演算法來判斷欲新增進來的物件是否與已經存在的某物件相等,從而建立物件的唯一性。實現Set介面的類有HashSet,TreeSet。

13.TreeSet是一個有序集合,TreeSet中元素將按照升序排列,預設是按照自然順序進行排列,意味著TreeSet中元素要實現Comparable介面。可以在構造TreeSet物件時,傳遞實現了Comparator介面的比較器物件。HashSet是基於Hash演算法實現的,其效能通常都優於TreeSet。通常使用HashSet,需要排序的功能時,使用TreeSet。

14.Map介面的實現類主要有HashMap,TreeMap,Hashtable,Properties。

(1)Hashtable,Properties是JDK1.0/1.1中的。

(2)HashMap對key進行雜湊。

(3)TreeMap按照key進行排序。

(4)和Set類似,HashMap的速度通常都比TreeMap快,只有在需要排序的功能的時候,才使用TreeMap。

15.集合框架為程式設計師提供了一個功能強大的設計方案以解決程式設計過程中面臨的大多數任務。 

實驗十一   集合

實驗時間 2018-11-8

1、實驗目的與要求

(1) 掌握Vetor、Stack、Hashtable三個類的用途及常用API;

(2) 瞭解java集合框架體系組成;

(3) 掌握ArrayList、LinkList兩個類的用途及常用API。

(4) 瞭解HashSet類、TreeSet類的用途及常用API。

(5)瞭解HashMap、TreeMap兩個類的用途及常用API;

(6) 結對程式設計(Pair programming)練習,體驗程式開發中的兩人合作。

2、實驗內容和步驟

實驗1: 匯入第9章示例程式,測試程式並進行程式碼註釋。

測試程式1:

l 使用JDK命令執行編輯、執行以下三個示例程式,結合執行結果理解程式;

l 掌握Vetor、Stack、Hashtable三個類的用途及常用API。 

//示例程式1

import java.util.Vector;

 

class Cat {

private int catNumber;

 

Cat(int i) {

catNumber = i;

}

 

void print() {

System.out.println("Cat #" + catNumber);

}

}

 

class Dog {

private int dogNumber;

 

Dog(int i) {

dogNumber = i;

}

 

void print() {

System.out.println("Dog #" + dogNumber);

}

}

 

public class CatsAndDogs {

public static void main(String[] args) {

Vector cats = new Vector();

for (int i = 0; i < 7; i++)

cats.addElement(new Cat(i));

cats.addElement(new Dog(7));

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

((Cat) cats.elementAt(i)).print();

}

}

//示例程式2

import java.util.*;

 

public class Stacks {

static String[] months = { "1", "2", "3", "4" };

 

public static void main(String[] args) {

Stack stk = new Stack();

for (int i = 0; i < months.length; i++)

stk.push(months[i]);

System.out.println(stk);

System.out.println("element 2=" + stk.elementAt(2));

while (!stk.empty())

System.out.println(stk.pop());

}

}

//示例程式3

import java.util.*;

 

class Counter {

int i = 1;

 

public String toString() {

return Integer.toString(i);

}

}

 

public class Statistics {

public static void main(String[] args) {

Hashtable ht = new Hashtable();

for (int i = 0; i < 10000; i++) {

Integer r = new Integer((int) (Math.random() * 20));

if (ht.containsKey(r))

((Counter) ht.get(r)).i++;

else

ht.put(r, new Counter());

}

System.out.println(ht);

}

}

package stackTrace;
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();//生成Vector類物件cats
        for (int i = 0; i < 7; i++)
            cats.addElement(new Cat(i));
        cats.addElement(new Cat(7));
        for (int i = 0; i < cats.size(); i++) 
            ((Cat) cats.elementAt(i)).print();
            
    }
}

package stackTrace;
import java.util.*;

public class Stacks {
    static String[] months = { "4", "5", "6", "7" };

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

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));//隨機生成20個r值
            if (ht.containsKey(r))//判斷引數是否是雜湊表中的鍵值
                ((Counter) ht.get(r)).i++;//引用Counter的屬性,輸出r出現的頻次
            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");

   }

}

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("mayun!");
        ListIterator li = l.listIterator(0);//迭代的物件生成器
        while (li.hasNext())//通過hasNext方法依次訪問
            System.out.println(li.next());
        if (l.indexOf("Hello") < 0)   //通過l呼叫indexOf方法
            System.err.println("Lookup does not work");
        else
            System.err.println("today is two 11");
   }
}

l 在Elipse環境下編輯執行除錯教材360頁程式9-1,結合程式執行結果理解程式;

l 掌握ArrayList、LinkList兩個類的用途及常用API。

package linkedList;

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

      // merge the words from b into a

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

      // remove every second word from b

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

測試程式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());

        }

    }

}

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

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

  }

}

package stackTrace;
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,結合程式執行結果理解程式;

l 瞭解HashMap、TreeMap兩個類的用途及常用API。

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

實驗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,結合使用體驗對所執行程式提出完善建議;

package text8;

 

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.List;

import java.util.Scanner;

 

public class Xinxi {

    private static ArrayList<Student> 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();

                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) {//新增的異常處理語句try{   }catch{   }語句

            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.尋找年齡相近的人的資訊");

 

            System.out.println("5.退出");

            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("家鄉在哪裡?");

                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;

 

            case "4":

                System.out.println("年齡:");

                int yourage = scanner.nextInt();

                int near = agenear(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 agenear(int age) {

        int j = 0, min = 53, value = 0, flag = 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;

                flag = i;

            }

        }

        return flag;

    }

 

} 
package text8;

 

public  class Student implements Comparable<Student> {

 

    private String name;

    private String number;

    private String sex;

    private String province;

    private int age;

 

    public void setName(String name) {

        // TODO 自動生成的方法存根

        this.name = name;

 

    }

 

    public String getName() {

        // TODO 自動生成的方法存根

        return name;

    }

 

    public void setnumber(String number) {

        // TODO 自動生成的方法存根

        this.number = number;

    }

 

    public String getNumber() {

        // TODO 自動生成的方法存根

        return number;

    }

 

    public void setsex(String sex) {

        // TODO 自動生成的方法存根

        this.sex = sex;

    }

 

    public String getsex() {

        // TODO 自動生成的方法存根

        return sex;

    }

 

    public void setprovince(String province) {

        // TODO 自動生成的方法存根

        this.province = province;

    }

 

    public String getprovince() {

        // TODO 自動生成的方法存根

        return province;

    }

 

    public void setage(int a) {

        // TODO 自動生成的方法存根

        this.age = age;

    }

 

    public int getage() {

        // TODO 自動生成的方法存根

        return age;

    }

 

    public int compareTo(Student o) {

        return this.name.compareTo(o.getName());

    }

 

    public String toString() {

        return name + "\t" + sex + "\t" + age + "\t" + number + "\t" + province + "\n";

    }

}

l 各自執行合作伙伴實驗十程式設計練習2,結合使用體驗對所執行程式提出完善建議;

package 第九周;

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

            // 使用者的答案要從鍵盤輸入,因此需要一個鍵盤輸入流

            Scanner in = new Scanner(System.in);

            yunsuan counter = new yunsuan  ();

            PrintWriter out = null;

             

            try {

                out = new PrintWriter("D:\\text.txt");

            } catch (FileNotFoundException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            int sum = 0;

            // 通過迴圈生成10道題

            for (int i = 0; i < 10; i++) {

             

                 

                int a = (int) Math.round(Math.random() * 100);

                int b = (int) Math.round(Math.random() * 100);

                 

                //Scanner in1 =new Scanner(System.in);

                 

                Random rand=new Random();

                switch((int)(Math.random()*4)+1)

                 

                {

                 

                case 1:

                System.out.println( ""+a+"+"+b+"=");

                 

                int c= in.nextInt();

                out.println(a+"+"+b+"="+c);

                if (c == counter.add(a, b)) {

                    sum += 10;

                    System.out.println("恭喜答案正確");

                }

                else {

                    System.out.println("抱歉答案錯誤");

                }

                 

                break ;

                case 2:

                    while (a<b) {

                        b = (int)Math.round(Math.random() * 100); ;

                         

                    }

                System.out.println(i + ": " + a + "-" + b + "=");

                int c1 = in.nextInt();

                out.println(a + "-" + b + "=" + c1);

                if (c1 == counter.reduce(a, b)) {

                    sum += 10;

                    System.out.println("恭喜答案正確");

                } else {

                    System.out.println("抱歉答案錯誤");

                }

                break;

                case 3:

                System.out.println(i + ": " + a + "*" + b + "=");

                int c2 = in.nextInt();

                out.println(a + "*" + b + "=" + c2);

                if (c2 == counter.multiplication(a, b)) {

                    sum += 10;

                    System.out.println("恭喜答案正確");

                } else {

                    System.out.println("抱歉答案錯誤");

                }

                break;

                case 4:

                 

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

                     

                }

                System.out.println(""+a+"/"+b+"=");

             int c3= in.nextInt();

             out.println(a+"/"+b+"="+c3);

             if (c3 == counter.devision(a, b)) {

                 sum += 10;

                 System.out.println("恭喜答案正確");

             }

             else {

                 System.out.println("抱歉答案錯誤");

             }

             break;

             }

            }

             

                System.out.println("總分:"+sum);

                out.println(sum);

                 

                out.close();

                }

                }
package 第九周;

 

public class yunsuan<T>{

    private T a;

    private T b;

    public yunsuan() {

        a=null;

        b=null;

    }

 

    public int multiplication(int a, int b) {

        // TODO 自動生成的方法存根

        return a*b;

    }

 

    public int add(int a, int b) {

        // TODO 自動生成的方法存根

        return a+b;

    }

 

    public int reduce(int a, int b) {

        // TODO 自動生成的方法存根

        if((a-b)>0)//保證兩數相減不會是負數

        return a-b;

        else

            return 0;

    }

     

    public int devision(int a, int b) {

        // TODO 自動生成的方法存根

        if (b != 0 && a%b==0)//保證是整除

        return a/b;

        else

            return 0;

    }

 

}

 

l 採用結對程式設計方式,與學習夥伴合作完成實驗九程式設計練習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.Scanner;

import java.util.Collections;//對集合進行排序、查詢、修改等;

 

public class Test {

    private static ArrayList<Citizen> citizenlist;

 

    public static void main(String[] args) {

        citizenlist = new ArrayList<>();

        Scanner scanner = new Scanner(System.in);

        File file = new File("E:/java/身份證號.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 id = linescanner.next();

                String sex = linescanner.next();

                String age = linescanner.next();

                String birthplace = linescanner.nextLine();

                Citizen citizen = new Citizen();

                citizen.setName(name);

                citizen.setId(id);

                citizen.setSex(sex);

                // 將字串轉換成10進位制數

                int ag = Integer.parseInt(age);

                citizen.setage(ag);

                citizen.setBirthplace(birthplace);

                citizenlist.add(citizen);

 

            }

        } 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.退出");

            int nextInt = scanner.nextInt();

            switch (nextInt) {

            case 1:

                Collections.sort(citizenlist);

                System.out.println(citizenlist.toString());

                break;

            case 2:

                int max = 0, min = 100;

                int m, k1 = 0, k2 = 0;

                for (int i = 1; i < citizenlist.size(); i++) {

                    m = citizenlist.get(i).getage();

                    if (m > max) {

                        max = m;

                        k1 = i;

                    }

                    if (m < min) {

                        min = m;

                        k2 = i;

                    }

                }

                System.out.println("年齡最大:" + citizenlist.get(k1));

                System.out.println("年齡最小:" + citizenlist.get(k2));

                break;

            case 3:

                System.out.println("出生地:");

                String find = scanner.next();

                String place = find.substring(0, 3);

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

                    if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place))

                        System.out.println("出生地" + citizenlist.get(i));

                }

                break;

            case 4:

                System.out.println("年齡:");

                int yourage = scanner.nextInt();

                int near = peer(yourage);

                int j = yourage - citizenlist.get(near).getage();

                System.out.println("" + citizenlist.get(near));

                break;

            case 5:

                isTrue = false;

                System.out.println("程式已退出!");

                break;

            default:

                System.out.println("輸入有誤");

            }

        }

    }

 

    public static int peer(int age) {

        int flag = 0;

        int min = 53, j = 0;

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

            j = citizenlist.get(i).getage() - age;

            if (j < 0)

                j = -j;

            if (j < min) {

                min = j;

                flag = i;

            }

        }

        return flag;

    }

}
public class Citizen implements Comparable<Citizen> {

 

    priv