第十週課上測試補作

第十週課上測試補作

1、相關知識點的總結

1.++鏈表++:由若干個稱做結點的==對象==組成的一種數據結構,每一個結點含有一個數據和下一個結點的引用,或含有一個數據並含有上一個結點的引用和下一個結點的引用。
2.建立鏈表:用java.util包中的```LinkedList 泛型類建立
例如
java

LinkedList<String> mylist = new LinkedList<String>();

3.添加結點:add(E obj)
例如:mylist.add("How")git

4.經常使用方法算法

5.遍歷鏈表:sql

  • 用++迭代器++遍歷集合:鏈表對象用iterator()方法得到一個Iterator對象.
  • get(int index)方法返回列表中的第index個對象。

6.排序與查找:編程

  • public static sort(List<E> list):將list中的元素按升序排列。
  • int binarySearch(List<T> list, T key, CompareTo<T> c):使用折半法查找list是否含有和參數key相等的元素,若是key與鏈表中的某個元素相等,方法返回和key相等的元素在鏈表中的索引位置(從0開始),不然返回-1.
  • 鏈表中存放的對象是String類數據:則字符串按字典序比較大小
  • 鏈表中存放的對象不是字符串數據:建立對象的類必須實現Comparable接口,即實現該接口中的方法int compareTo(Object b)來規定對象的大小關係。

2、課上內容的補作,結果截圖

課上題目2:數組

在數據結構和算法中,排序是很重要的操做,要讓一個類能夠進行排序,有兩種方法:數據結構

  • 有類的源代碼,針對某一成員變量排序,讓類實現Comparable接口,調用Collection.sort(List)
  • 沒有類的源代碼,或者多種排序,新建一個類,實現Comparator接口,調用Collection.sort(List, Compatator)

針對下面的Student類,使用Comparator編程完成如下功能:數據結構和算法

  1. 在測試類StudentTest中新建學生列表,包括本身和學號先後各兩名學生,共5名學生,給出運行結果(排序前,排序後)
  2. 對這5名同窗分別用學號和總成績進行增序排序,提交兩個Comparator的代碼
  3. 課下提交代碼到碼雲

分析:由於題目中屬於多種排序,因此,要新建一個類,並讓類實現Comparator接口,並重寫接口中的int ComparaTo(Object b)方法。ide

課題代碼:代碼學習

代碼:

import java.util.*;
import java.text.*;

//重寫接口中Compare方法
class Compare1 implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        Student st1 = (Student)o1;
        Student st2 = (Student)o2;
        int id1 = Integer.parseInt(((Student) o1).getId());
        int id2 = Integer.parseInt(((Student) o2).getId());
        return (id1 - id2);
    }
}

class Compare2 implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        Student st1 = (Student) o1;
        Student st2 = (Student) o2;
        if (st1.getTotalScore() == st2.getTotalScore()) {
            return 0;
        }
        if (st1.getTotalScore() > st2.getTotalScore()) {
            return 1;
        }
        if (st1.getTotalScore() <= st2.getTotalScore()) {
            return -1;
        }
        return 0;
    }
}

class StudentTest {
    public static void main(String[] args) {
        List<Student> list = new LinkedList<Student>();//建立一個list鏈表
        //向鏈表中添加結點(對象)
        list.add(new Student("20165201", "李梓豪",90,91,95));
        list.add(new Student("20165202", "賈海粟",89,93,92));
        list.add(new Student("20165203", "夏雲霄",93,95,92));
        list.add(new Student("20165204", "賈普涵",88,90,91));
        list.add(new Student("20165205", "劉喆君",87,90,92));
        Iterator<Student> iter = list.iterator();//list鏈表對象用iterator方法獲取一個Iterator對象(針對當前鏈表的迭代器)
        System.out.println("排序前,鏈表中的數據");
        while (iter.hasNext()) {
            Student stu = iter.next();
            System.out.println(stu.getId() + " " + stu.getName() + " 總成績:" + stu.getTotalScore());
        }
        Collections.sort(list,new Compare1());//調用接口中的Compare1方法來就id來排序
        System.out.println("按學號排序後,鏈表中的數據");
        iter = list.iterator();
        while (iter.hasNext()){
            Student stu = iter.next();
            System.out.println(stu.getId() + " " + stu.getName() + " 總成績:" + stu.getTotalScore());
        }
        Collections.sort(list,new Compare2());//調用接口中的Compare2方法來就總分來排序
        System.out.println("按總成績排序後,鏈表中的數據");
        iter = list.iterator();
        while (iter.hasNext()){
            Student stu = iter.next();
            System.out.println(stu.getId() + " " + stu.getName() + " 總成績:" + stu.getTotalScore());
        }
    }
}

class Student {
    private char sex;
    private String id;//表示學號
    private String name;//表示姓名
    private int age;//表示年齡
    private double computer_score;//表示計算機課程的成績
    private double english_score;//表示英語課的成績
    private double maths_score;//表示數學課的成績
    private double total_score;// 表示總成績
    private double ave_score; //表示平均成績

    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public Student(String id, String name, char sex, int age) {
        this(id, name);
        this.sex = sex;
        this.age = age;
    }
    public Student(String id, String name, double computer_score, double english_score, double maths_score) {
        this(id, name);
        this.computer_score = computer_score;
        this.english_score = english_score;
        this.maths_score = maths_score;
    }
    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }//得到當前對象的學號,

    public double getComputer_score() {
        return computer_score;
    }//得到當前對象的計算機課程成績,

    public double getMaths_score() {
        return maths_score;
    }//得到當前對象的數學課程成績,

    public double getEnglish_score() {
        return english_score;
    }//得到當前對象的英語課程成績,

    public void setId(String id) {
        this.id = id;
    }// 設置當前對象的id值,

    public void setComputer_score(double computer_score) {
        this.computer_score = computer_score;
    }//設置當前對象的Computer_score值,

    public void setEnglish_score(double english_score) {
        this.english_score = english_score;
    }//設置當前對象的English_score值,

    public void setMaths_score(double maths_score) {
        this.maths_score = maths_score;
    }//設置當前對象的Maths_score值,

    public double getTotalScore() {
        return computer_score + maths_score + english_score;
    }// 計算Computer_score, Maths_score 和English_score 三門課的總成績。

    public double getAveScore() {
        return getTotalScore() / 3;

    }// 計算Computer_score, Maths_score 和English_score 三門課的平均成績。

}

class Undergraduate extends Student {
    private String classID;

    public Undergraduate(String id, String name, char sex, int age, String classID) {
        super(id, name, sex, age);
        this.classID = classID;
    }

    public String getClassID() {
        return classID;
    }

    public void setClassID(String classID) {
        this.classID = classID;
    }
}

結果截圖:

課上題目3:
參見附件,補充MyList.java的內容,提交運行結果截圖(全屏)
課下推送代碼到碼雲

課題代碼:代碼

代碼:

import java.util.*;
public class MyList {
    public static void main(String [] args) {
        List<String> list=new LinkedList<String>();
        list.add("20165201");
        list.add("20165202");
        list.add("20165204");
        list.add("20165205");
        System.out.println("打印初始鏈表");
        //把上面四個節點連成一個沒有頭結點的單鏈表
        Iterator<String> iter=list.iterator();
        while(iter.hasNext()){
            String te=iter.next();
            System.out.println(te);
        }
        //遍歷單鏈表,打印每一個結點的
        list.add("20165203");
        //把你本身插入到合適的位置(學號升序)
        System.out.println("插入個人學號後排序,打印鏈表");
        Collections.sort(list);
        iter=list.iterator();
        while(iter.hasNext()){
            String te=iter.next();
            System.out.println(te);
        }
        //遍歷單鏈表,打印每一個結點的
        list.remove("20165203");
        //從鏈表中刪除本身
        System.out.println("刪除個人學號後打印鏈表");
        iter=list.iterator();
        while(iter.hasNext()){
            String te=iter.next();
            System.out.println(te);
        }
        //遍歷單鏈表,打印每一個結點的
    }
}

結果截圖:

分析:本例中添加了插入、排序、刪除等內容,本身在作插入時,卻在「如何插入到正確位置」這個位置上犯了難。 後來,本身通過思考,發現該鏈表中的結點都是String類,String類中實現了Comparable接口,Collection調用sort排序時,字符串按字典序比較大小,不用重寫compareTo方法。

3、教材第十五章的代碼分析

1.Example15_1系列代碼分析:

Cone.java
Rect.java
Circle.java
Example15_1.java
這個程序範例很好,幫助我理解了泛型類的概念,Cone.java表示的是計算一個椎體的體積,由於底面的形狀不肯定,因此,可用泛型類表示底面。以後又定義了Rect.java(計算矩形的面積),Circle.java(計算圓的面積),來在主程序中計算椎體的體積。

2.Example15_2分析:

Example15_2.java

這個程序主要講的是鏈表的遍歷,值得學習的是:
利用Iterator<String> iter = list.iterator();建立了一個針對list鏈表的迭代器。
本身對程序中不懂的代碼進行了學習:

  • iter.hasNext():該語句的做用是判斷鏈表中下一個結點是不是空結點,若是不是返回true,是返回fale,可用於循環語句中。

  • iter.next():該語句也是用來判斷列表中下一個結點是不是空結點,若是不是,返回下一個結點.

關鍵代碼分析:

Iterator<String> iter=list.iterator();//建立一個iter鏈表迭代器  
 long starttime=System.currentTimeMillis();//以毫秒爲單位計算開始使的時間  
 //遍歷整個鏈表,將鏈表中的節點賦給te數組
 while(iter.hasNext()){
           String te=iter.next();
      }

3.Example15_3分析:

Example15_3.java

該程序的亮點是利用add(Object obj)向鏈表中依次添加結點
利用get()獲取一個結點中的對象時,要用類型轉換運算符轉換回原來的類型。

關鍵代碼分析:

Iterator iter=mylist.iterator();//獲取針對mylist鏈表的迭代器
while(iter.hasNext()) {
    String te=(String)iter.next();  //必須強制轉換取出的數據
    System.out.println(te);
}

4.Example15_4分析:

Example15_4

這個程序的功能是排序,讓我學到了很多東西。
該程序中鏈表中存放的Studnet類對象並非字符串型的,因此,要讓Studnet類實現Comparable接口,實現該接口中的compare To(Object b)方法。

程序:

public int compareTo(Object b) { // 兩個Student對象相等當且僅當兩者的height值相等
     Student st=(Student)b;
     return (this.height-st.height);
   }

給出了排序的根據:兩個結點相等的根據是對象的height相等。height值大的排在後面。

關鍵代碼分析:

//經過重寫compareTo方法規定排序的依據
class Student implements Comparable { 
   int height=0;
   String name;
   Student(String n,int h) {
      name=n;
      height = h;
     
   }
   public int compareTo(Object b) { // 兩個Student對象相等當且僅當兩者的height值相等
     Student st=(Student)b;
     return (this.height-st.height);
   }
}

5.Example15_5分析:

Example15_5

該程序主要體現了洗牌,所謂洗牌就是將鏈表中的數據從新隨機排列,可用public static void shuffle(List<E> list)

  • static void rotate(List<E> list, int distance):distance取正值,向右轉動;distance取負值,向左轉動。
  • public static void reverse(List<E> list):翻轉list中的數據。

關鍵代碼分析:

Collections.shuffle(list);//洗牌後的從新操做
Collections.rotate(list,1);//向右旋轉1次後的操做

6.Example15_6分析:

Example15_6

該程序主要是建立了一個堆棧對象stack,並在stack中放入對象,而後輸出該遞歸序列的若干項.

關鍵代碼分析:

Stack<Integer> stack=new Stack<Integer>();//建立一個堆棧對象
//向堆棧中放入對象,注意堆棧中的元素是對象
      stack.push(new Integer(1));
      stack.push(new Integer(1));
int f1=F1.intValue();//吧Integer類型轉化爲int類型

7.Example15_7分析:

Example15_7.java
WindowWord.java
WordPolice.java
本程序主要體現散列映射的意義,主要是存儲數據便於查找,該程序就是用WordPolice類使用Scanner解析word.txt中的單詞,並將英文單詞/漢語對應鍵/值存儲到散列映射中供用戶查詢。

8.Example15_8分析:

Example15_8.java

本程序體現了用樹集存放時,若是對象不是字符串類型,要重寫compareTo方法規定排序方法。本程序中,貴司可以排序爲按照英語成績,因此,在樹集中的存放方式要按照英語成績存放。

9.Example15_9分析:

Example15_9.java

本程序主要是建立樹映射,並存儲關鍵字/值對,重寫compareTo方法,而後分別對該樹中的結點按英語成績和數學成績排序。

10.Example15_10分析:

Example15_10

該程序體現了自動裝箱和自動拆箱。將鏈表中的int型數據轉換成Integer對象,輸出時,將Integer對象轉換成int類型。

4、第15章課下編程題

1.使用堆棧結構輸出an的若干項,其中an=2an-1+2an-1,a1=3,a2=8

分析:編程思路以下:

  • 定義堆棧
  • 將數列前兩項放入堆棧
  • 計算第三項,依次循環

代碼以下:

import java.util.*;
public class Exp1 {
    public static void main(String args[]) {
        Stack<Integer> stack = new Stack<Integer>();//定義一個空堆棧
        //將數列前兩項放入堆棧中
        stack.push(3);
        stack.push(8);
        int k = 1;
        //輸出15項
        while (k <= 15) {
            for (int i = 1; i <= 2; i++) {
                Integer F1=stack.pop();
                int f1 = F1.intValue();
                Integer F2=stack.pop();
                int f2 = F2.intValue();
                Integer temp = 2*f1+2*f2;
                System.out.println(" "+temp.toString());
                stack.push(temp);
                stack.push(F2);
                k++;
            }

        }
    }
}

2.編寫一個程序,將鏈表中的學生英語成績單存放到一個樹集中,使得按成績自動排序,並輸出排序結果。

代碼:

import java.util.*;

import static java.sql.DriverManager.println;

class College implements Comparable {
    int english=0;
    String name;
    College(String name, int english ){
        this.name=name;
        this.english=english;
    }
    public int comparaTo(Object b) {
        College stu = (College) b;
        return (this.english-stu.english);
    }
}
public class Exp2 {
    public static void main(String args[]) {
        List<College> list=new LinkedList<College>();
        int score [] = {85,88,90,91,88};
        String name [] = {"李梓豪","賈海粟","夏雲霄","賈普涵","劉喆君"};
        for(int i=0; i<score.length;i++){
            list.add(new College(name[i],score[i]));
        }
        Iterator<College> iter = list.iterator();
        TreeSet<College> mytree=new TreeSet<College>();
        while(iter.hasNext()) {
            College stu=iter.next();
            mytree.add(stu);
        }
        Iterator<College> te=mytree.iterator();
        while(te.hasNext()) {
            College stu = iter.next();
            System.out.println(""+stu.name+" "+stu.english);
        }

    }
}

3.三、有10個U盤,有兩個重要的屬性:價格和容量。編寫一個應用程序,使用TreeMap

import java.util.*; 
class SandyKey implements Comparable {
     double key=0;
     SandyKey(double d) {
      key=d;
    } 
   public int compareTo(Object b) {
      SandyKey disc=(SandyKey)b; 
     if((this.key-disc.key)==0)
         return -1;
      else 
        return (int)((this.key-disc.key)*1000);
   }
 } 
class Sandy{
      int amount;
     double price; 
    Sandy(int m,double e) {
        amount=m;
         price=e;
    }
 } 
public class E { 
   public static void main(String args[ ]) { 
      TreeMap<SandyKey,Sandy>  treemap= new TreeMap<SandyKey,Sandy>();
       int amount[]={1,2,4,8,16};
       double price[]={867,266,390,556};
       Sandy Sandy[]=new Sandy[4];
       for(int k=0;k<Sandy.length;k++) { 
         Sandy[k]=new Sandy(amount[k],price[k]);
       } 
      SandyKey key[]=new SandyKey[4];
        for(int k=0;k<key.length;k++) { 
         key[k]=new SandyKey(Sandy[k].amount);        } 
      for(int k=0;k<Sandy.length;k++) { 
         treemap.put(key[k],Sandy[k]);                 } 
      int number=treemap.size(); 
      Collection<Sandy> collection=treemap.values();
       Iterator<Sandy> iter=collection.iterator();
       while(iter.hasNext()) {
          Sandy sandy=iter.next(); 
         System.out.println(""+sandy.amount+"G "+sandy.price+"元");       } 
      treemap.clear(); 
      for(int k=0;k<key.length;k++) { 
 key[k]=new SandyKey(Sandy[k].price);       } 
      for(int k=0;k<Sandy.length;k++) {
          treemap.put(key[k],Sandy[k]);       } 
      number=treemap.size();
       collection=treemap.values();
       iter=collection.iterator();
       while(iter.hasNext()) {
          Sandy sandy=iter.next(); 
         System.out.println(""+sandy.amount+"G "+sandy.price+"元");
       }
     }
 }
相關文章
相關標籤/搜索