Supplementary test in the tenth week of class

Supplementary test in the tenth week of class

1. Summary of relevant knowledge points

1.++ linked list++: a data structure consisting of a number of == objects == called nodes, each node contains a data and a reference to the next node, or contains a data and contains the previous A reference to one node and a reference to the next node.
2. Create a linked list: use java.utilthe ````LinkedList in the package

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

3. Add a node: add(E obj)
For example:mylist.add("How")

4. Common methods

5. Traverse the linked list:

  • Traverse a collection with ++iterator++: a linked list object uses a iterator()method to get an Iteratorobject.
  • get(int index)Returns the index-th object in the list with the method.

6. Sort and find:

  • public static sort(List<E> list): Arranges the elements in the list in ascending order.
  • int binarySearch(List<T> list, T key, CompareTo<T> c): Use the halving method to find whether the list contains an element equal to the parameter key. If the key is equal to an element in the linked list, the method returns the index position (starting from 0) of the element equal to the key in the linked list, otherwise it returns -1.
  • The objects stored in the linked list are Stringclass data: the strings are lexicographically compared in size
  • The objects stored in the linked list are not string data: the class that creates the object must implement Comparablethe interface, that is, implement the methods in the interface int compareTo(Object b)to specify the size relationship of the object.

2. Supplementation of the content in the class, screenshots of the results

Class topic 2:

In data structures and algorithms, sorting is a very important operation. To make a class can be sorted, there are two ways:

  • There is a source code of a class, sort a member variable, let the class implement the Comparable interface, and call Collection.sort(List)
  • If there is no source code of the class, or multiple sorts, create a new class, implement the Comparator interface, and call Collection.sort(List, Compatator)

For the following Student class, use Comparator programming to complete the following functions:

  1. Create a new student list in the test class StudentTest, including two students before and after oneself and student number, a total of 5 students, and give the running results (before sorting, after sorting)
  2. Sort these 5 students in increasing order by student number and total score, and submit the codes of two Comparators
  3. Submit code to Code Cloud after class

Analysis: Because the title belongs to a variety of sorting, so, to create a new class, and let the class implement the Comparator interface, and rewrite the int ComparaTo(Object b)methods in the interface.

Subject Code: Code

Code:

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

Result screenshot:

Class topic 3:
See the attachment, supplement the content of MyList.java, submit a screenshot of the running result (full screen)
and push the code to the code cloud after class

Subject Code: Code

Code:


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);
        }
        //遍历单链表,打印每个结点的
    }
}

Result screenshot:

Analysis: In this example, inserting, sorting, deleting, etc. are added, but when inserting by myself, I have made difficulties in the position of "how to insert into the correct position". Later, after thinking about it, I found that the nodes in the linked list are all Stringclasses, Stringwhich are implemented in the class. When the Comparable接口Collection calls sort, the strings are compared in lexicographical order, and the compareTo method does not need to be rewritten.

3. Code Analysis in Chapter 15 of the textbook

1.Example15_1 series code analysis:

Cone.java
Rect.java
Circle.java
Example15_1.java
This program example is very good and helped me understand the concept of generic classes. Cone.java represents the calculation of the volume of a cone, because the shape of the bottom surface is uncertain, so, The underside can be represented with a generic class. After that, Rect.java (calculating the area of ​​the rectangle) and Circle.java (calculating the area of ​​the circle) are defined to calculate the volume of the vertebral body in the main program.

2.Example15_2 analysis:

Example15_2.java

This program mainly talks about the traversal of the linked list. It is worth learning that: an iterator for the list linked list is created by
using it. I learned the code I didn’t understand in the program myself:Iterator<String> iter = list.iterator();

  • iter.hasNext(): The function of this statement is to determine whether the next node in the linked list is an empty node. If it does not return true, it returns false, which can be used in loop statements.

  • iter.next(): This statement is also used to determine whether the next node in the list is an empty node, if not, return to the next node.

Key code analysis:

 Iterator<String> iter=list.iterator();//创建一个iter链表迭代器  
 long starttime=System.currentTimeMillis();//以毫秒为单位计算开始使的时间  
 //遍历整个链表,将链表中的节点赋给te数组
 while(iter.hasNext()){
           String te=iter.next();
      }

3.Example15_3 analysis:

Example15_3.java

The highlight of this program is to use add(Object obj)the addition of nodes to the linked list in turn. When obtaining an object in a node,
use get()the type conversion operator to convert it back to the original type.

Key code analysis:

Iterator iter=mylist.iterator();//获取针对mylist链表的迭代器
while(iter.hasNext()) {
    String te=(String)iter.next();  //必须强制转换取出的数据
    System.out.println(te);
}  

4.Example15_4 analysis:

Example15_4

The function of this program is sorting, which taught me a lot.
The Studnet class object stored in the linked list in this program is not a string type, so let the Studnet class implement the Comparable interface and implement the compare To(Object b) method in the interface.

program:

public int compareTo(Object b) { // 两个Student对象相等当且仅当二者的height值相等
     Student st=(Student)b;
     return (this.height-st.height);
   }  

The basis for sorting is given: the basis for the equality of two nodes is that the heights of the objects are equal. The ones with the larger height value are in the back.

Key code analysis:

//通过重写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 analysis:

Example15_5

This program mainly embodies shuffling. The so-called shuffling is to rearrange the data in the linked list randomly.public static void shuffle(List<E> list)

  • static void rotate(List<E> list, int distance):distance takes a positive value and rotates to the right; distance takes a negative value and rotates to the left.
  • public static void reverse(List<E> list): Flip the data in the list.

Key code analysis:

Collections.shuffle(list);//洗牌后的重新操作
Collections.rotate(list,1);//向右旋转1次后的操作   

6.Example15_6 analysis:

Example15_6

The program mainly creates a stack object stack, puts objects in the stack, and then outputs several items of the recursive sequence.

Key code analysis:

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 analysis:

Example15_7.java
WindowWord.java
WordPolice.java
This program mainly embodies the meaning of hash mapping, mainly to store data for easy search. This program uses the WordPolice class to use Scanner to parse the words in word.txt, and convert English words/Chinese corresponding keys / The value is stored in a hash map for user query.

8.Example15_8 analysis:

Example15_8.java

This program embodies that when the tree set is used to store, if the object is not a string type, the compareTo method should be rewritten to specify the sorting method. In this program, your company can be sorted according to English scores, so the storage method in the tree set should be stored according to English scores.

9.Example15_9 analysis:

Example15_9.java

This program mainly creates a tree map, stores keyword/value pairs, rewrites the compareTo method, and then sorts the nodes in the tree according to English scores and math scores.

10.Example15_10 Analysis:

Example15_10

The program embodies autoboxing and auto-unboxing. Convert the int data in the linked list to an Integer object, and convert the Integer object to an int when outputting.

4. Chapter 15 After-Class Programming Questions

1. Use the stack structure to output several items of an, where an=2an-1+2an-1, a1=3, a2=8

Analysis: The programming ideas are as follows:

  • define stack
  • Put the first two items of the sequence on the stack
  • Calculate the third item, loop in turn

code show as below:


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. Write a program to store the students' English transcripts in the linked list into a tree set, so that the results are automatically sorted and the sorting results are output.

Code:

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.3. There are 10 U disks with two important attributes: price and capacity. Write an application that uses 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+"元");
       }
     }
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325455586&siteId=291194637