IMG-LOGO
×

Tài Liệu Học

Khoá học lập trình Java Core nâng cao

Exception & Collection

[Video] Tìm hiểu exception + debug + package - lập trình Java Nâng Cao [Video] Tìm hiểu collections, Sets, Maps và Generic - lập trình java nâng cao [Video] Chương trình quản lý sinh viên bằng HashMap - Java Advanced

File

[Video] Hướng dẫn đọc ghi file FileInputStream, FileOutputStream, ObjectInputStream trong java - lập trình java nâng cao [Video] Bài tập quản lý sách & lưu thông tin trên Files [Video] File - Quản lý thông tin sinh viên [Video] Quản lý thông tin sinh & lưu object file - Java nâng cao [Video] Viết ứng dụng WinRar | WinZip | 7Zip bằng Java - Nén file Java & giải nén file Java - Khoá học Java [Video] Bài tập quản lý bán vé máy bay - java nâng cao

Thread

[Video] Phân tích quản lý ứng dụng trong HĐH (Window, Mac, Linux)-Phân tích Game đa luồng Java [Video] Tìm hiểu Thread - Đồng bộ Thread - lập trình java nâng cao - Bổ sung thêm lớp học mới. [Video] Giải thích synchronized + Lap trinh Java nang cao [Video] Thread thực hiện in ngẫu nhiên các số nguyên và ký tự - Phần 1 [Video] Thread thực hiện in ngẫu nhiên các số nguyên và ký tự & Đông bộ thread + wait notify + synchronized + Java nâng cao - Phần 2 [Video] Synchronized 2 Thread - Bài tập mảng tên + địa chỉ - Java nâng cao [Video] Bài tập ôn luyện tổng hợp File, OOP, Thread trong java [Video] Sử dụng MultiThreading sinh ký tự a-zA-Z trong java

CSDL

[Video] Kết nối MySQL trong java swing JDBC trong java - lập trình java nâng cao [Video] Kết nối CSDL bằng java swing phần 1 - lập trình java nâng cao [Video] Kết nối CSDL bằng java swing phần 2 - lập trình java nâng cao [Video] Chương trình quản lý thư viện Java + XML Java + CSDL Java- SQL Java [Video] Phần mềm quản lý sinh viên MySQL + Java - Chương trình quản lý sinh viên MySQL + Java - Lập Trình Java [Video] Bài Tập Quản Lý Sinh Viên - CSDL - Java Swing [Video] Chương trình quản lý sản phẩm - quản lý tin tức - quản lý bán hàng - Lập trình Java [Video] Chức năng register & login + CSDL - Lập trình Java nâng cao - Phần 1 [Video] Hướng dẫn sử dụng Persistence Java - Kết nối database Java - MySQL Java nâng cao

Design Pattern & Đa Ngôn Ngữ

[Video] Design Pattern lập trình java nâng cao - lập trình java nâng cao

XML & JSON & CSDL

[Video] C1 > Chương trình quản lý sinh viên Java + Import/Export JSON + File - Lập Trình Java [Video] C2 > Chương trình quản lý sinh viên Java + Import/Export JSON + File - Lập Trình Java

Ôn Tập Tổng Quát & Exmination

[Video] Bài tập - Chường trình quản lý sở thú - Lập trình Java - Lập trình Java nâng cao - Phần 1 [Video] Bài tập - Chường trình quản lý sở thú - Lập trình Java - Lập trình Java nâng cao - Phần 2




Trang Chủ Java Advanced Quản lý thông tin sinh & lưu object file - Java nâng cao

Quản lý thông tin sinh & lưu object file - Java nâng cao

by GokiSoft.com - 16:42 29/10/2021 4,376 Lượt Xem

Viết chương trình quản lý sinh viên. Mỗi đối tượng sinh viên có các thuộc tính sau: id, name, age, address và gpa (điểm trung bình). Yêu cầu: tạo ra một menu với các chức năng sau: 

/****************************************/
1. Add student.
2. Edit student by id.
3. Delete student by id.
4. Sort student by gpa.
5. Sort student by name.
6. Show student.

7. Lưu thông tin sv vào file student.obj

8. Đọc thông tin sv từ file student.obj và hiển thị ra màn hình
0. Exit.
/****************************************/

Bình luận



Chia sẻ từ lớp học

Lê Sỹ Khai [community,C2009G]

Ngày viết: 23:32 13/09/2021


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package studentmanager1;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author LE KHAI
 */
public class Main {
    public static void main(String[] args) {
       StudentController st = new StudentController();
        int choice;
        do {            
            showMenu();
            choice = Integer.parseInt((new Scanner(System.in)).nextLine());
            switch(choice){
                case 1:                    
                    st.addStudent();
                    break;
                
                case 2:
                    st.editStudentById();
                    break;
                
                case 3:
                   st.deleteStudentById();
                   break;
                   
                case 4:
                    st.sortStudentByGpa();
                    break;
                    
                case 5:
                    st.sortStudentByName();
                    break;
                    
                case 6:
                    st.showStudent();
                    break;
                    
                case 7:
                    st.saveFileStudentObj();
                    break;
                    
                case 8: 
                    st.readFileObj();
                    break;
                    
                case 0:
                    System.out.println("Thoat");
                    break;
                    
                default:
                    System.out.println("Nhap sai. Nhap lai lua chon: ");
                    break;
            }
        } while (choice != 0);
        
    }

    private static void showMenu() {
        System.out.println("1. Add student");
        System.out.println("2. Edit student by id");
        System.out.println("3. Delete student by id");
        System.out.println("4. Sort student by gpa");
        System.out.println("5. Sort student by name");
        System.out.println("6. Show student");
        System.out.println("7. Luu thong tin file student.obj");
        System.out.println("8. Doc thong tin tu file obj và hien thi ra man hinh");
        System.out.println("0. Exit");
        System.out.println("\nNhap lua chon cua ban: ");        
    }

}


#Student.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package studentmanager1;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author LE KHAI
 */
public class Student implements Serializable{
    String id, name, address;
    int age;
    double gpa;

    public Student() {
    }

    public Student(String id, String name, String address, int age, double gpa) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.age = age;
        this.gpa = gpa;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getGpa() {
        return gpa;
    }

    public void setGpa(double gpa) {
        this.gpa = gpa;
    }
    public  void input(){
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhap id: ");
        id = scan.nextLine();
        
        System.out.println("Nhap ten: ");
        name = scan.nextLine();
        
        System.out.println("Nhap tuoi: ");
        age =Integer.parseInt(scan.nextLine());
        
        System.out.println("Nhap dia chi: ");
        address = scan.nextLine();
        
        System.out.println("Nhap diem trung binh: ");
        gpa = Double.parseDouble(scan.nextLine());           
    }
    
    public void show(){
        System.out.println(String.format("Id: %s, Ten: %s, Tuoi: %d, Dia Chi: %s, Diem Trung Binh: %.1f", 
                                         id, name, age, address, gpa));
    }

    @Override
    public String toString() {
        return  "id=" + id + ", name=" + name + ", address=" + address + ", age=" + age + ", gpa=" + gpa + "\n";
    }
    
}


#StudentController.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package studentmanager1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author LE KHAI
 */
public class StudentController {
    List<Student> listStudent = new ArrayList<>();
    public void addStudent() {
        
        System.out.println("Nhap so luong muon them: ");
        int n = Integer.parseInt((new Scanner(System.in)).nextLine());                   
                    for (int i = 0; i < n; i++) {
                        Student student = new Student();
                        student.input();
                        listStudent.add(student);
                    }
        System.out.println("Da them thanh cong\n");
    }
    
    public void editStudentById(){
        boolean isExisted = false;
        System.out.println("Nhap Id can sua: ");
        String findId = (new Scanner(System.in)).nextLine();
        for (Student student : listStudent) {
            if (student.getId().equals(findId)) {
                isExisted = true;
                student.input();
                System.out.println("Da sua thanh cong\n");
            }
        }
        if(!isExisted){
            System.out.println("Khong ton tai id: "+findId);
        }
    }
    
    public void deleteStudentById(){
        Boolean isExisted = false;
        System.out.println("Nhap Id can xoa: ");
        String deleteId = (new Scanner(System.in)).nextLine();
        for (Student student : listStudent) {
            if(student.getId().equals(deleteId)){
                isExisted = true;
                listStudent.remove(student);
                System.out.println("Da xoa id: "+deleteId);
            }
        }
        if(!isExisted){
            System.out.println("Khong ton tai Id: "+deleteId);
        }
    }
    
    public void sortStudentByGpa() {
        Collections.sort(listStudent, new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getGpa() > o2.getGpa() ? 1 : -1 ;
            }          
        });
        System.out.println("Sort student by gpa succcess! ");
    }
    
    public void sortStudentByName() {      
        Collections.sort(listStudent, new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
              return o1.getName().compareToIgnoreCase(o2.getName());
            }          
        });  
        System.out.println("Sort student by name succcess! ");
    }
    
    public void showStudent(){
        System.out.println("Danh sach sinh vien: ");
        for (Student student : listStudent) {
            student.show();
        }
    }
    
    public void saveFileStudentObj() {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("student.obj");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(listStudent);
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } 
        System.out.println("Save file success!");
    }
    
    public void readFileObj() {
      FileInputStream  fis = null;
      ObjectInputStream ois = null;
        try {
            fis = new FileInputStream("student.obj");
            ois = new ObjectInputStream(fis);
            List<Student> dataList = (List<Student>)ois.readObject();
            for (Student student : dataList) {
                System.out.println(student.toString());
            }
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } 
    }
    
}


Hieu Ngo [community,C2009G]

Ngày viết: 09:41 08/09/2021


#Main.java


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String [] args) {
        int x;
        List<Student> students;
        students = new ArrayList<>();
        do {
            System.out.println("1. Add student.");
            System.out.println("2. Edit student by id.");
            System.out.println("3. Delete student by id.");
            System.out.println("4. Sort student by gpa.");
            System.out.println("5. Sort student by name.");
            System.out.println("6. Show student.");
            System.out.println("7. Lưu thông tin sv vào file student.obj");
            System.out.println("8. Đọc thông tin sv từ file student.obj và hiển thị ra màn hình");
            System.out.println("0. Exit.");
            System.out.println("Your choice:");
            x = (new Scanner(System.in)).nextInt();
            switch (x) {
                case 1:
                    System.out.println("Enter number of student");
                    int n = (new Scanner(System.in)).nextInt();
                    for(int i =0; i<n ;i++) {
                        Student student = new Student();
                        student.input();
                        students.add(student);
                    }
                    break;
                case 2:
                    boolean isFind = false;
                    System.out.println("Nhap id can sua:");
                    String findId = (new Scanner(System.in)).next();
                    for(Student student : students) {
                        if(student.getId().equals(findId)) {
                            student.input();
                            isFind = true;
                            break;
                        }
                    }
                    if(!isFind){
                        System.out.println("Khong co sinh vien nao co id = "+ findId);
                    }
                    break;
                case 3:
                    isFind = false;
                    System.out.println("Nhap id can xoa");
                    String deleteId = (new Scanner(System.in)).nextLine();
                    for(Student deleteStudent : students) {
                        if(deleteStudent.getId().equals(deleteId)) {
                            isFind = true;
                            students.remove(deleteStudent);
                            break;
                        }
                    }
                    if(!isFind){
                        System.out.println("Khong co sinh vien nao co id = "+ deleteId);
                    }
                    break;
                case 4:
                    Collections.sort(students, new Comparator<Student>() {
                        @Override
                        public int compare(Student o1, Student o2) {
                            if(o1.getGpa() < o1.getGpa()) {
                                return 1;
                            }
                            return -1;
                        }
                    });
                    System.out.println("Sap xep theo GPA thanh cong....");
                    break;
                case 5:
                    Collections.sort(students, new Comparator<Student>() {
                        @Override
                        public int compare(Student o1, Student o2) {
                            return o1.getName().compareTo(o2.getName());
                        }
                    });
                    System.out.println("Sap xep theo ten thanh cong....");
                    break;
                case 6 :
                    for (Student student : students) {
                        student.display();
                    }
                    break;
                case 7:
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;

                    try {
                        fos = new FileOutputStream("data.obj");
                        oos = new ObjectOutputStream(fos);
                        oos.writeObject(students);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (oos != null) {
                            try {
                                oos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                case 8:
                    FileInputStream fis = null;
                    ObjectInputStream ois = null;

                    try {
                        fis = new FileInputStream("data.obj");
                        ois = new ObjectInputStream(fis);
                        students = (List<Student>) ois.readObject();
                        for (Student student : students) {
                            student.display();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        if(fis!=null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if(ois!=null) {
                            try {
                                ois.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                case 0:
                    return;
            }
        } while (x>=0 && x <= 8);
    }
}


#Student.java


import java.io.Serializable;
import java.util.Scanner;

public class Student implements Serializable {
    private String id, name, address;
    private Integer age;
    private Float gpa;

    public Student() {
    }

    public Student(String id, String name, String address, Integer age, Float gpa) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.age = age;
        this.gpa = gpa;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Float getGpa() {
        return gpa;
    }

    public void setGpa(Float gpa) {
        this.gpa = gpa;
    }
    public Scanner getScanner() {
        return new Scanner(System.in);
    }

    public void input() {
        System.out.println("Enter id:");
        this.id = getScanner().nextLine();
        System.out.println("Enter name:");
        this.name = getScanner().nextLine();
        System.out.println("Enter age:");
        this.age = getScanner().nextInt();
        System.out.println("Address:");
        this.address = getScanner().nextLine();
        System.out.println("GPA :");
        this.gpa = getScanner().nextFloat();
    }

    public void display() {
        System.out.println(String.format("id = %s, name= %s, age=%d, address=%s, GPA=%.2f",this.id,this.name,this.age,this.address,this.gpa));
    }
}


GokiSoft.com [Teacher]

Ngày viết: 20:03 17/08/2021


#Utility.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03.bt1052;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Utility {
    public static int scanInt(Scanner scan) {
        int value;
        while(true) {
            try {
                value = Integer.parseInt(scan.nextLine());
                break;
            } catch(NumberFormatException e) {
                System.out.println("Nhap lai: ");
            }
        }
        return value;
    }
    
    public static float scanFloat(Scanner scan) {
        float value;
        while(true) {
            try {
                value = Float.parseFloat(scan.nextLine());
                break;
            } catch(NumberFormatException e) {
                System.out.println("Nhap lai: ");
            }
        }
        return value;
    }
}


#Student.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03.bt1052;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Student implements Serializable{
    int id, age;
    String name, address;
    float gpa;

    public Student() {
    }

    public Student(int id, int age, String name, String address, float gpa) {
        this.id = id;
        this.age = age;
        this.name = name;
        this.address = address;
        this.gpa = gpa;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public float getGpa() {
        return gpa;
    }

    public void setGpa(float gpa) {
        this.gpa = gpa;
    }

    @Override
    public String toString() {
        return "id=" + id + ", age=" + age + ", name=" + name + ", address=" + address + ", gpa=" + gpa;
    }
    
    public void display() {
        System.out.println(this);
    }
    
    public void edit() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Nhap Tuoi: ");
        age = Utility.scanInt(scan);
        
        System.out.println("Nhap Ten: ");
        name = scan.nextLine();
        
        System.out.println("Nhap Dia Chi: ");
        address = scan.nextLine();
        
        System.out.println("Nhap Diem GPA: ");
        gpa = Utility.scanFloat(scan);
    }
    
    public void input() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhap ID: ");
        id = Utility.scanInt(scan);
        
        edit();
    }
}


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03.bt1052;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        DataController controller = DataController.getInstance();
        
        Scanner scan = new Scanner(System.in);
        int choose;
        
        do {
            showMenu();
            choose = Utility.scanInt(scan);
            
            switch (choose) {
                case 1:
                    controller.input();
                    break;
                case 2:
                    controller.display();
                    break;
                case 3:
                    controller.edit();
                    break;
                case 4:
                    controller.delete();
                    break;
                case 5:
                    controller.sortByGpa();
                    controller.display();
                    break;
                case 6:
                    controller.sortByName();
                    controller.display();
                    break;
                case 7:
                    controller.saveFile();
                    break;
                case 8:
                    controller.readFile();
                    controller.display();
                    break;
                case 9:
                    System.out.println("Thoat!!!");
                    break;
                default:
                    System.out.println("Nhap sai!!!");
                    break;
            }
        } while(choose != 9);
    }
    
    static void showMenu() {
        System.out.println("1. Nhap sinh vien");
        System.out.println("2. Hien thi sinh vien");
        System.out.println("3. Sua sinh vien theo ID");
        System.out.println("4. Xoa sinh vien theo ID");
        System.out.println("5. Sap xep theo GPA");
        System.out.println("6. Sap xep theo ten");
        System.out.println("7. Luu students.obj");
        System.out.println("8. Doc du lieu students.obj");
        System.out.println("9. Thoat!!!");
        System.out.println("Chon: ");
    }
}


#DataController.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03.bt1052;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Singleton
 * @author Diep.Tran
 */
public class DataController {
    List<Student> studentList;
    Scanner scan;
    
    private static DataController instance = null;
    
    private DataController() {
        studentList = new ArrayList<>();
        scan = new Scanner(System.in);
    }
    
    public static DataController getInstance() {
        if(instance == null) {
            instance = new DataController();
        }
        return instance;
    }
    
    public void input() {
        System.out.println("Nhap so sinh vien can them: ");
        int N = Utility.scanInt(scan);
        
        for (int i = 0; i < N; i++) {
            Student std = new Student();
            std.input();
            
            studentList.add(std);
        }
    }
    
    public void display() {
        System.out.println("Thong tin sinh vien: ");
        studentList.forEach(student -> {
            student.display();
        });
    }
    
    public void edit() {
        System.out.println("Nhap id can sua: ");
        int id = Utility.scanInt(scan);
        
        boolean isFind = false;
        for (Student student : studentList) {
            if(student.getId() == id) {
                //thuc hien sua du lieu
                isFind = true;
                student.edit();
                break;
            }
        }
        
        if(!isFind) {
            System.out.println("Khong tim thay sinh vien co id = " + id);
        }
    }
    
    public void delete() {
        System.out.println("Nhap id can xoa: ");
        int id = Utility.scanInt(scan);
        
        boolean isFind = false;
        for (Student student : studentList) {
            if(student.getId() == id) {
                //thuc hien sua du lieu
                isFind = true;
                studentList.remove(student);
                break;
            }
        }
        
        if(!isFind) {
            System.out.println("Khong tim thay sinh vien co id = " + id);
        }
    }
    
    public void sortByGpa() {
        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.getGpa() < o2.getGpa()) {
                    return -1;
                }
                return 1;
            }
        });
        System.out.println("Sap xep theo GPA thanh cong ...");
    }
    
    public void sortByName() {
        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareToIgnoreCase(o2.getName());
            }
        });
        System.out.println("Sap xep theo Name thanh cong ...");
    }
    
    public void saveFile() {
        //Mode ghi du lieu.
        System.out.println("Chon che do ghi: ");
        System.out.println("1. Ghi them");
        System.out.println("2. Ghi de");
        System.out.println("Chon: ");
        int choose = Utility.scanInt(scan);
        
        boolean append = false;
        if(choose == 1) {
            append = true;
        }
        
        //THuc hien luu thong tin du lieu
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            fos = new FileOutputStream("students.obj", append);
            oos = new ObjectOutputStream(fos);
            
            for (Student student : studentList) {
                oos.writeObject(student);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        System.out.println("Luu thanh cong " + studentList.size() + " sinh vien");
    }
    
    public void readFile() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream("students.obj");
            ois = new ObjectInputStream(fis);
            
            while(true) {
                try {
                    Student std = (Student) ois.readObject();
                    studentList.add(std);
                } catch(Exception e) {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        }  finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        System.out.println("Thuc hien doc xong du lieu...");
    }
}


Trần Văn Điệp [Teacher]

Ngày viết: 12:36 25/03/2020

Source Code



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bt18;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author teacher
 */
public class Student implements Serializable{
    String fullname;
    int id;
    String address;
    int age;
    float gpa;

    public Student() {
    }

    public Student(String fullname, int id, String address, int age, float gpa) {
        this.fullname = fullname;
        this.id = id;
        this.address = address;
        this.age = age;
        this.gpa = gpa;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public float getGpa() {
        return gpa;
    }

    public void setGpa(float gpa) {
        this.gpa = gpa;
    }

    @Override
    public String toString() {
        return "Student{" + "fullname=" + fullname + ", id=" + id + ", address=" + address + ", age=" + age + ", gpa=" + gpa + '}';
    }
    
    public void display() {
        System.out.println(toString());
    }
    
    public void input() {
        Scanner input = new Scanner(System.in);
        
        System.out.println("Nhap ID : ");
        id = Integer.parseInt(input.nextLine());
        
        inputWithoutId();
    }
    
    public void inputWithoutId() {
        Scanner input = new Scanner(System.in);
        
        System.out.println("Nhap ten : ");
        fullname = input.nextLine();
        System.out.println("Nhap dia chi : ");
        address = input.nextLine();
        System.out.println("Nhap tuoi : ");
        age = Integer.parseInt(input.nextLine());
        System.out.println("Nhap diem trung binh : ");
        gpa = Float.parseFloat(input.nextLine());
    }
}




/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bt18;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author teacher
 */
public class Main {

    static List<Student> studentList = new ArrayList<>();
    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        int choose;

        do {
            showMenu();
            choose = Integer.parseInt(input.nextLine());
            switch (choose) {
                case 1:
                    input();
                    break;
                case 2:
                    editById();
                    break;
                case 3:
                    deleteById();
                    break;
                case 4:
                    sortByGpa();
                    break;
                case 5:
                    sortByName();
                    break;
                case 6:
                    showAll();
                    break;
                case 7:
                    saveIntoFile();
                    break;
                case 8:
                    readDataFromFile();
                    break;
                case 9:
                    System.out.println("Exit!!!");
                    break;
                default:
                    System.out.println("Input failed!");
                    break;
            }
        } while (choose != 9);
    }

    static void input() {
        System.out.println("Nhap so sinh vien can them : ");
        int n = Integer.parseInt(input.nextLine());

        for (int i = 0; i < n; i++) {
            Student std = new Student();
            std.input();
            studentList.add(std);
        }
    }

    static void editById() {
        System.out.println("Nhap ID can sua : ");
        int id = Integer.parseInt(input.nextLine());

        for (Student student : studentList) {
            if (student.getId() == id) {
                //sua
                student.inputWithoutId();
                break;
            }
        }
    }

    static void deleteById() {
        System.out.println("Nhap ID can xoa : ");
        int id = Integer.parseInt(input.nextLine());

        for (Student student : studentList) {
            if (student.getId() == id) {
                //sua
                studentList.remove(student);
                break;
            }
        }
    }

    static void sortByGpa() {
        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return (o1.getGpa() > o2.getGpa()) ? 1 : -1;
            }
        });
    }

    static void sortByName() {
        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getFullname().compareTo(o2.getFullname());
            }
        });
    }

    static void showAll() {
        for (Student student : studentList) {
            student.display();
        }
    }

    static void saveIntoFile() {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            fos = new FileOutputStream("student.dat");
            oos = new ObjectOutputStream(fos);

            oos.writeObject(studentList);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    static void readDataFromFile() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;

        try {
            fis = new FileInputStream("student.dat");
            ois = new ObjectInputStream(fis);

            studentList = (List<Student>) ois.readObject();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    static void showMenu() {
        System.out.println("1. Add student");
        System.out.println("2. Edit student by ID");
        System.out.println("3. Delete student by ID");
        System.out.println("4. Sort student list by GPA");
        System.out.println("5. Sort student list by Name");
        System.out.println("6. Show All Stundent");
        System.out.println("7. Save all student into student.dat");
        System.out.println("8. Read file student.dat and show all");
        System.out.println("9. Exit");
        System.out.println("Choose : ");
    }
}


Phân Loại Bài Viết

Tài Liệu Tham Khảo

Đã sao chép!!!