1. 程式人生 > >第十二週Java實驗作業

第十二週Java實驗作業

實驗十一   集合

實驗時間 2018-11-8

1、實驗目的與要求

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

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

Vetor類關鍵屬性:

capacity表示集合最多能容納的元素個數。

capacityIncrement表示每次增加多少容量。

siize集合當前元素個數。

Vector v = new Vector (100);

StackVector的子類。

Stack類描述堆疊資料結構,即

LIFO 

Stack類的關鍵方法:

public void push(Object item)//把棧壓入棧頂

public Object pop()//移除棧頂物件並作為此函式的值返回物件

public Object peek()//檢視棧頂物件而不移除它

Public boolean empty()//推測堆疊是否為空

Hashtable通過鍵來查詢元素。

Hastable用雜湊碼(hastable)來確定鍵。所有物件都有有一個雜湊碼,可以通過Object類的hastable()方法獲得。

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

 

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

ArrayList可以將其看作是能夠自動增長容量的陣列。

利用ArrayList類的toArray返回一個數組。

Arrays.asList()返回一個列表。

LinkedList是採用雙向迴圈列表實現的。

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

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

(6) 結對程式設計(Pair programming

)練習,體驗程式開發中的兩人合作。

2、實驗內容和步驟

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

測試程式1:

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

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

出現執行時異常,輸出Dog #7 時,型別不匹配。附上兩種修改方法。 

示例程式1:

package 小陳;
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()-1; i++) {
            System.out.println(cats.get(i).getClass());//獲得類名
            //if(cats.get(i).getClass()  )
            ((Cat) cats.elementAt(i)).print();
    }
        System.out.println(cats.get(7).getClass());//獲得類名
        ((Dog) cats.elementAt(7)).print();
    }
}
/*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 < 7; i++) {
            System.out.println(cats.get(i).getClass());//獲得類名
            //if(cats.get(i).getClass()  )
            ((Cat) cats.elementAt(i)).print();
        for ( i = 0; i < cats.size(); i++) {
            System.out.println(cats.get(i).getClass());//獲得類名
            //if(cats.get(i).getClass()  )
            ((Dog) cats.elementAt(i)).print();
        }
    }
        System.out.println(cats.get(7).getClass());//獲得類名
        ((Dog) cats.elementAt(7)).print();
    }

}*/

/*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++) {
            System.out.println(cats.get(i).getClass());//獲得類名
            if(cats.elementAt(i) instanceof Cat)
            {
                ((Cat) cats.elementAt(i)).print();
            }else {
                ((Dog) cats.elementAt(i)).print();
            }
    }
    }
}*/
CatsAndDogs

執行結果:

                

 示例程式2:

package 小陳3.src;

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

執行結果:

示例程式3:

package 小陳1;
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));
//使用Math.random方法生成整型隨機數r,範圍是0到20
            if (ht.containsKey(r))
//通過物件呼叫containsKey(),判斷r值是否是雜湊表裡的鍵值,如果是,返回true,否則返回false
                ((Counter) ht.get(r)).i++;//獲得雜湊表裡面的鍵值,引用Counter的屬性,輸出r出現的頻次
            else
                ht.put(r, new Counter());//呼叫put方法向雜湊表裡面新增鍵值
        }
        System.out.println(ht);
    }
}
Statistics

執行結果:

測試程式3:

l 使用JDK命令編輯執行ArrayListDemo和LinkedListDemo兩個程式,結合程式執行結果理解程式;

package 小陳3;
import java.util.*;

public class ArrayListDemo {
    public static void main(String[] argv) {
        ArrayList<Comparable> al = new ArrayList<Comparable>();
        // 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:");
        //System.out.println(al.size());//輸出al陣列的長度
        for (int i = 0; i < al.size(); i++) {
            System.out.println("Element " + i + " = " + al.get(i));//get方法存放索引值
        }
    }
}
ArrayListDemo

執行結果:

package 小陳4;
import java.util.*;
public class LinkedListDemo {
    public static void main(String[] argv) {
        LinkedList l = new LinkedList();//構造一個空連結串列,實質為建立一個數組
        l.add(new Object());//呼叫add方法向連結串列新增元素
        l.add("Hello");
        l.add("zhangsan");
        ListIterator li = l.listIterator(0);//構造一個迭代器
        while (li.hasNext())
            //hasNext() 用於檢查序列中是否還有元素,如果仍然有元素可以迭代,則返回true,返回迭代的下一個元素
            System.out.println(li.next());//next()返回當前next()的一個物件
        if (l.indexOf("Hello") < 0)   
            System.err.println("Lookup does not work");
        else
            System.err.println("Lookup works");
   }
}
LinkListDemo.

執行結果:

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<>();//構造一個空連結串列,實質為建立一個String型別的陣列a
      a.add("Amy");//呼叫add方法向陣列新增元素
      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,將a陣列的內容合併到b中

      ListIterator<String> aIter = a.listIterator();
      //使用LinkList類的listIterator方法返回一個實現了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,從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);
   }
}
LinkedListTest

測試程式3:

l 執行SetDemo程式,結合執行結果理解程式;

package 小陳3.src;
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,利用HashSet實現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.");
   }
}
SetTest

執行結果:

l 在Elipse環境下除錯教材367頁-368程式9-3、9-4,結合程式執行結果理解程式;瞭解TreeSet類的用途及常用API。

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

執行結果:

測試程式4:

l 使用JDK命令執行HashMapDemo程式,結合程式執行結果理解程式;

package treeSet;
import java.util.*;
public class HashMapDemo {
   public static void main(String[] argv) {
      HashMap h = new HashMap();//構造一個空雜湊對映
      // The hash maps from company name to address.
      h.put("Adobe", "Mountain View, CA");//將這些元素插入到對映中
      h.put("IBM", "White Plains, NY");
      h.put("Sun", "Mountain View, CA");
      String queryString = "Adobe";
      String resultString = (String)h.get(queryString);
      System.out.println("They are located in: " +  resultString);
  }
}
HashMapDemo

執行結果:

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

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

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"));//a將員工資訊新增到對映中
      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));
   }
}
MapTest
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 + "]";
   }
}
Employee

執行結果:

實驗2:結對程式設計練習:

l 關於結對程式設計:以下圖片是一個結對程式設計場景:兩位學習夥伴坐在一起,面對著同一臺顯示器,使用著同一鍵盤,同一個滑鼠,他們一起思考問題,一起分析問題,一起編寫程式。

l 關於結對程式設計的闡述可參見以下連結:

 

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

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

l 對於結對程式設計中程式碼設計規範的要求參考:

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

 

以下實驗,就讓我們來體驗一下結對程式設計的魅力。

l 確定本次實驗結對程式設計合作伙伴;

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

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

l 採用結對程式設計方式,與學習夥伴合作完成實驗九程式設計練習1;

l 採用結對程式設計方式,與學習夥伴合作完成實驗十程式設計練習2。

合作伙伴:王燕

合作伙伴的程式碼:

身份證號檔案處理:

package 看到誰;
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 Check{
    private static ArrayList<Student> studentlist;
    public static void main(String[] args) {
        studentlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("C:\\下載\\身份證號.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) {//捕獲異常
            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 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("老鄉"+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,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;         
      }

}
Check
package 看到誰;
public class Student implements Comparable<Student> {

    private String name;
    private String number ;
    private String sex ;
    private int age;
    private String province;
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getnumber() {
        return number;
    }
    public void setnumber(String number) {
        this.number = number;
    }
    public String getsex() {
        return sex ;
    }
    public void setsex(String sex ) {
        this.sex =sex ;
    }
    public int getage() {

        return age;
        }
        public void setage(int age) {
            // int a = Integer.parseInt(age);
        this.age= age;
        }

    public String getprovince() {
        return province;
    }
    public void setprovince(String province) {
        this.province=province ;
    }

    public int compareTo(Student o) {
       return this.name.compareTo(o.getName());
    }//對姓名進行字典排序

    public String toString() {
        return  name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
    }    
}
Student

簡易計算器:

package 看到誰;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Caculator {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Caculator1 computing=new Caculator1();
        PrintWriter output = null;
        //使用了異常處理機制,增強程式碼的安全性
        try {
            output = new PrintWriter("Caculator.txt");
        } catch (Exception e) {
        }
        int sum = 0;
            //隨機數生成,提供後續題目所用的資料
        for (int i = 1; i < 11; i++) {
            int a = (int) Math.round(Math.random() * 100);
            int b = (int) Math.round(Math.random() * 100);
            int s = (int) Math.round(Math.random() * 3);
            //選擇所要進行的操作
        switch(s)//s為隨機數,可隨機執行下面四種操作
        {
           case 1:
               System.out.println(i+": "+a+"/"+b+"=");
               while(b==0){  
                   b = (int) Math.round(Math.random() * 100); 
                   }
               double c = in.nextDouble();
               output.println(a+"/"+b+"="+c);
               //修改建議:生成除法題目時,對a,b兩個數進行條件判斷,確保整除,還有除數不為0
               if (c == (double)computing.division(a, b)) {
                   sum += 10;
                   System.out.println("T");
               }
               else {
                   System.out.println("F");
               }
            
               break;
            //
           case 2:
               System.out.println(i+": "+a+"*"+b+"=");
               int c1 = in.nextInt();
               output.println(a+"*"+b+"="+c1);
               if (c1 == computing.multiplication(a, b)) {
                   sum += 10;
                   System.out.println("T");
               }
               else {
                   System.out.println("F");
               }
               break;
           case 3:
               System.out.println(i+": "+a+"+"+b+"=");
               int c2 = in.nextInt();
               output.println(a+"+"+b+"="+c2);
               if (c2 == computing.addition(a, b)) {
                   sum += 10;
                   System.out.println("T");
               }
               else {
                   System.out.println("F");
               }
               
               break ;
           case 4:
               System.out.println(i+": "+a+"-"+b+"=");
               int c3 = in.nextInt();
               output.println(a+"-"+b+"="+c3);
               if (c3 == computing.subtraction(a, b)) {
                   sum += 10;
                   System.out.println("T");
               }
               else {
                   System.out.println("F");
               }
               break ;

               } 
    
          }
        System.out.println("scores:"+sum);
        output.println("scores:"+sum);
        output.close();
         
    }
}
class Caculator1
{
       private int a;
       private int b;
        public int  addition(int a,int b)
        {
            return a+b;
        }
        public int  subtraction(int a,int b)
        {
            if((a-b)<0)
                return 0;
            else
            return a-b;
        }
        public int   multiplication(int a,int b)
        {
            return a*b;
        }
        public int   division(int a,int b)
        {
            if(b!=0)
            return a/b;    
            else
        return 0;
        }

        
}
四則運算

合作程式碼:

 身份證號檔案處理:

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 Identity{
    private static ArrayList<Student> studentlist;
    public static void main(String[] args) {
        studentlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("C:/身份證號.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) {
            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("0.退出");
            int status = scanner.nextInt();
            switch (status) {
            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 0:
                    status = 0;
                    System.out.println("程式已退出!");
                    break;
               default:
                   System.out.println("輸入錯誤");
               }
             }
            }
        public static int agenear(int age) {      
        int 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;         
      }
      
}
Identity
package 看到誰;

public  class Student implements Comparable<Student> {
    private    String name;
    private    String number ;
    private    String sex ;
    private    int age;
    private    String province;
 
     
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getnumber() {
        return number;
    }
    public void setnumber(String number) {
        this.number = number;
    }
    public String getsex() {
        return sex ;
    }
    public void setsex(String sex ) {
        this.sex =sex ;
    }
    public int getage() {
        return age;
    }
    public void setage(int age ) {
        this.age=age ;
    }
    public String getprovince() {
        return province;
    }
    public void setprovince(String province) {
        this.province=province ;
    }
@Override
public int compareTo(Student other) {
    // TODO Auto-generated method stub
     return this.name.compareTo(other.getName());
}

public String toString() {
    return  name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
}    
}
Student

執行結果:

 

簡易計算器:

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Caculator {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Caculator1 computing=new Caculator1();
        PrintWriter output = null;
        try {
            output = new PrintWriter("Caculator.txt");
        } catch (Exception e) {
        }
        int sum = 0;

        for (int i = 1; i < 11; i++) {
            int a = (int) Math.round(Math.random() * 100);
            int b = (int) Math.round(Math.random() * 100);
            int s = (int) Math.round(Math.random() * 3);
        switch(s)
        {
           case 1:
               System.out.println(i+": "+a+"/"+b+"=");
               while(b==0){  
                   b = (int) Math.round(Math.random() * 100); 
                   }
               double c = in.nextDouble();
               output.println(a+"/"+b+"="+c);
               if (c == (double)computing.division(a, b)) {
                   sum += 10;
                   System.out.println("T");
               }
               else {
                   System.out.println("F");
               }
            
               break;
            
           case 2:
               System.out.println(i+": "+a+"*"+b+"=");
               int c1 = in.nextInt();
               output.println(a+"*"+b+"="+c1);
               if (c1 == computing.multiplication(a, b)) {
                   sum += 10;
                   System.out.println("T");
               }
               else {
                   System.out.println("F");
               }
               break;
           case 3:
               System.out.println(i+": "+a+"+"+b+"=");
               int c2 = in.nextInt();
               output.println(a+"+"+b+"="+c2);
               if (c2 == computing.addition(a, b)) {
                   sum += 10;
                   System.out.println("T");
               }
               else {
                   System.out.println(