Bài tập java có lời giải chi tiết năm 2024

Trước khi theo dõi và học tập theo loạt ví dụ đa dạng về Java này, thì trước tiên bạn nên có kiến thức về Ngôn ngữ lập trình Java và các khái niệm của ngôn ngữ này.

Loạt bài bài tập Java có giải này được thiết kế cho người mới học để giúp các bạn hiểu hơn về các khái niệm từ cơ bản tới nâng cao liên quan tới Ngôn ngữ lập trình Java. Với từng bài tập, việc đầu tiên là bạn nên tự tìm cách giải, sau đó so sánh lời giải của mình với phần code minh họa của chúng mình. Với các lỗi hay gặp hay các lời giải hay hay với một phương thức, hàm có tác dụng đặc biệt, bạn nên note lại vào một nơi nào. Việc này sẽ giúp bạn nhớ và hiểu các khái niệm liên quan tới Java nhanh hơn.

Dưới đây là danh sách các bài tập Java có giải. Bạn vào đường link để theo dõi các bài tập Java theo từng chủ đề.

MỤC LỤC

Quảng cáo

  • Bài tập Java - Cài đặt môi trường
  • Bài tập Java - String
  • Bài tập Java - Array
  • Bài tập Java - Date & Time
  • Bài tập Java - Phương thức (Method)
  • Bài tập Java - File
  • Bài tập Java - Thư mục
  • Bài tập Java - Exception
  • Bài tập Java - Cấu trúc dữ liệu
  • Bài tập Java - Collection
  • Bài tập Java - Lập trình mạng
  • Bài tập Java - Thread
  • Bài tập Java - Applet
  • Bài tập Java - Java GUI
  • Bài tập Java - JDBC
  • Bài tập Java - Regular Exp

Trong quá trình biên soạn loạt bài tập Java có giải này có thể vẫn còn một số sai sót nào đó mà chúng mình chưa chú ý đến, mong các bạn đọc đóng góp ý kiến. Ý kiến đóng góp quý báu của các bạn là một trong những chìa khóa giúp chúng mình dần hoàn thiện các loạt bài hướng dẫn.

Loạt bài hướng dẫn Bài tập Java - 247 bài tập Java có giải của chúng tôi dựa trên nguồn tài liệu của: Tutorialspoint

Chú ý: Link các bài học ở menu bên trái. Nếu không xem được, vui lòng xem hướng dẫn tại đây

Đã có app VietJack trên điện thoại, giải bài tập SGK, SBT Soạn văn, Văn mẫu, Thi online, Bài giảng....miễn phí. Tải ngay ứng dụng trên Android và iOS.

Bài tập java có lời giải chi tiết năm 2024

Bài tập java có lời giải chi tiết năm 2024

Theo dõi chúng tôi miễn phí trên mạng xã hội facebook và youtube:

Các bạn có thể mua thêm khóa học JAVA CORE ONLINE VÀ ỨNG DỤNG cực hay, giúp các bạn vượt qua các dự án trên trường và đi thực tập Java. Khóa học có giá chỉ 300K, nhằm ưu đãi, tạo điều kiện cho sinh viên cho thể mua khóa học.

Nội dung khóa học gồm 16 chuơng và 100 video cực hay, học trực tiếp tại https://www.udemy.com/tu-tin-di-lam-voi-kien-thuc-ve-java-core-toan-tap/ Bạn nào có nhu cầu mua, inbox trực tiếp a Tuyền, cựu sinh viên Bách Khoa K53, fb: https://www.facebook.com/tuyen.vietjack

Follow facebook cá nhân Nguyễn Thanh Tuyền https://www.facebook.com/tuyen.vietjack để tiếp tục theo dõi các loạt bài mới nhất về Java,C,C++,Javascript,HTML,Python,Database,Mobile.... mới nhất của chúng tôi.

Đề bài: 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. 0. Exit. /****************************************/

Lời giải

Các bạn lưu ý: trước khi xem lời giải các bạn hãy tự làm trước nhé. Hãy coi lời giải này như một bài tham khảo.

1. Cấu trúc của project

Cấu trúc của project được tạo trên eclipse:

Bài tập java có lời giải chi tiết năm 2024

Trong đó:

  • Lớp Student để lưu thông tin cho mỗi sinh viên.
  • Lớp StudentDao để đọc và ghi sinh viên vào file.
  • Lớp SortStudentByGPA được implements Comparator để sắp xếp sinh viên tăng dần theo điểm trung bình.
  • Lớp SortStudentByName được implements Comparator để sắp xếp sinh viên tăng dần theo tên.
  • Lớp StudentManager cung cấp các phương thức để quản lý sinh viên như thêm, sửa, xóa, sắp xếp và hiển thị sinh viên.
  • Lớp Main chứa phương thức public static void main() để chạy ứng dụng và menu như yêu cầu của bài toán.

2. Tạo lớp Student.java

Lớp này để lưu thông tin cho mỗi sinh viên.

File: Student.java

`package vn.eLib; import java.io.Serializable; /

  • Student class
  • @author eLib.vn / public class Student implements Serializable { private int id; private String name; private byte age; private String address; / điểm trung bình của sinh viên */ private float gpa; public Student() {} public Student(int id, String name, byte age, String address, float gpa) {
    super();  
    this.id = id;  
    this.name = name;  
    this.age = age;  
    this.address = address;  
    this.gpa = gpa;  
    
    } public int getId() {
    return id;  
    
    } public void setId(int id) {
    this.id = id;  
    
    } public String getName() {
    return name;  
    
    } public void setName(String name) {
    this.name = name;  
    
    } public byte getAge() {
    return age;  
    
    } public void setAge(byte age) {
    this.age = age;  
    
    } 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;  
    
    } }`

3. Tạo lớp StudentDao.java

Tạo file "student.txt" tại thư mục gốc của dự án để lưu danh sách sinh viên.

Bài tập java có lời giải chi tiết năm 2024

Trong trường hợp này chúng ta sử dụng file để lưu trữ và truy xuất các đối tượng sinh vien. Nên lớp Student phải được implements Serializable.

Lớp StudentDao.java chứa phương thức read() để đọc thông tin danh sách sinh viên từ file "student.txt" và phương thức write() để ghi thông tin danh sách sinh viên vào file.

Phương thức read() sử dụng đối tượng ObjectInputStream trong java để đọc danh sách sinh viên từ file.

Phương thức write() sử dụng đối tượng ObjectOutputStream trong java để ghi danh sách sinh viên vào file.

File: StudentDao.java

`package vn.eLib; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /

  • StudentDao class
  • @author eLib.vn / public class StudentDao { private static final String STUDENT_FILE_NAME = "student.txt"; /*
    • save list student to file
    • @param studentList: list student to save
       /  
      
      public void write(List < Student > studentList) {
      FileOutputStream fos = null;  
      ObjectOutputStream oos = null;  
      try {  
        fos = new FileOutputStream(new File(STUDENT_FILE_NAME));  
        oos = new ObjectOutputStream(fos);  
        oos.writeObject(studentList);  
      } catch(FileNotFoundException e) {  
        e.printStackTrace();  
      } catch(IOException e) {  
        e.printStackTrace();  
      } finally {  
        closeStream(fos);  
        closeStream(oos);  
      }  
      
      } /*
    • read list student from file
    • @return list student
       /  
      
      public List < Student > read() {
      List < Student > studentList = new ArrayList < >();  
      FileInputStream fis = null;  
      ObjectInputStream ois = null;  
      try {  
        fis = new FileInputStream(new File(STUDENT_FILE_NAME));  
        ois = new ObjectInputStream(fis);  
        studentList = (List < Student > ) ois.readObject();  
      } catch(FileNotFoundException e) {  
        e.printStackTrace();  
      } catch(IOException e) {  
        e.printStackTrace();  
      } catch(ClassNotFoundException e) {  
        e.printStackTrace();  
      } finally {  
        closeStream(fis);  
        closeStream(ois);  
      }  
      return studentList;  
      
      } /*
    • close input stream
    • @param is: input stream
       /  
      
      private void closeStream(InputStream is) {
      if (is != null) {  
        try {  
          is.close();  
        } catch(IOException e) {  
          e.printStackTrace();  
        }  
      }  
      
      } /*
    • close output stream
    • @param os: output stream
       */  
      
      private void closeStream(OutputStream os) {
      if (os != null) {  
        try {  
          os.close();  
        } catch(IOException e) {  
          e.printStackTrace();  
        }  
      }  
      
      } }`

4. Tạo lớp SortStudentByGPA.java

Lớp SortStudentByGPA implements Comparator được sử dụng để sắp xếp sinh viên tăng dần theo điểm trung bình. Tìm hiểu thêm về cách sử dụng Comparator trong java.

File: SortStudentByGPA.java

`package vn.eLib; import java.util.Comparator; /

  • SortStudentByGPA class
  • @author eLib.vn */ public class SortStudentByGPA implements Comparator < Student > {@Override public int compare(Student student1, Student student2) {
    if (student1.getGpa() > student2.getGpa()) {  
      return 1;  
    }  
    return - 1;  
    
    } }`

5. Tạo lớp SortStudentByName.java

Lớp SortStudentByName implements Comparator được sử dụng để sắp xếp sinh viên tăng dần theo tên.

File: SortStudentByName.java

`package vn.eLib; import java.util.Comparator; /

  • SortStudentByName class
  • @author eLib.vn */ public class SortStudentByName implements Comparator < Student > {@Override public int compare(Student student1, Student student2) {
    return student1.getName().compareTo(student2.getName());  
    
    } }`

6. Tạo lớp StudentManager.java

Lớp này cung cấp các phương thức để thêm, sửa, xóa, sắp xếp và hiển thị sinh viên.

`package vn.eLib; import java.util.Collections; import java.util.List; import java.util.Scanner; /

  • StudentManager class
  • @author eLib.vn / public class StudentManager { public static Scanner scanner = new Scanner(System. in ); private List < Student > studentList; private StudentDao studentDao; /*
    • init StudentDao object and
    • read list student when init StudentManager object
       /  
      
      public StudentManager() {
      studentDao = new StudentDao();  
      studentList = studentDao.read();  
      
      } /*
    • add student to studentList
    • @param student
       /  
      
      public void add() {
      int id = (studentList.size() > 0) ? (studentList.size() + 1) : 1;  
      System.out.println("student id = " + id);  
      String name = inputName();  
      byte age = inputAge();  
      String address = inputAddress();  
      float gpa = inputGpa();  
      Student student = new Student(id, name, age, address, gpa);  
      studentList.add(student);  
      studentDao.write(studentList);  
      
      } /*
    • edit student by id
    • @param id
       /  
      
      public void edit(int id) {
      boolean isExisted = false;  
      int size = studentList.size();  
      for (int i = 0; i < size; i++) {  
        if (studentList.get(i).getId() == id) {  
          isExisted = true;  
          studentList.get(i).setName(inputName());  
          studentList.get(i).setAge(inputAge());  
          studentList.get(i).setAddress(inputAddress());  
          studentList.get(i).setGpa(inputGpa());  
          break;  
        }  
      }  
      if (!isExisted) {  
        System.out.printf("id = %d not existed.\n", id);  
      } else {  
        studentDao.write(studentList);  
      }  
      
      } /*
    • delete student by id
    • @param id: student id
       /  
      
      public void delete(int id) {
      Student student = null;  
      int size = studentList.size();  
      for (int i = 0; i < size; i++) {  
        if (studentList.get(i).getId() == id) {  
          student = studentList.get(i);  
          break;  
        }  
      }  
      if (student != null) {  
        studentList.remove(student);  
        studentDao.write(studentList);  
      } else {  
        System.out.printf("id = %d not existed.\n", id);  
      }  
      
      } /*
    • sort student by name
       /  
      
      public void sortStudentByName() {
      Collections.sort(studentList, new SortStudentByName());  
      
      } /*
    • sort student by id
       /  
      
      public void sortStudentByGPA() {
      Collections.sort(studentList, new SortStudentByGPA());  
      
      } /*
    • show list student to screen
       /  
      
      public void show() {
      for (Student student: studentList) {  
        System.out.format("%5d | ", student.getId());  
        System.out.format("%20s | ", student.getName());  
        System.out.format("%5d | ", student.getAge());  
        System.out.format("%20s | ", student.getAddress());  
        System.out.format("%10.1f%n", student.getGpa());  
      }  
      
      } /*
    • input student id
    • @return student id
       /  
      
      public int inputId() {
      System.out.print("Input student id: ");  
      while (true) {  
        try {  
          int id = Integer.parseInt((scanner.nextLine()));  
          return id;  
        } catch(NumberFormatException ex) {  
          System.out.print("invalid! Input student id again: ");  
        }  
      }  
      
      } /*
    • input student name
    • @return student name
       /  
      
      private String inputName() {
      System.out.print("Input student name: ");  
      return scanner.nextLine();  
      
      } /*
    • input student address
    • @return student address
       /  
      
      private String inputAddress() {
      System.out.print("Input student address: ");  
      return scanner.nextLine();  
      
      } /*
    • input student age
    • @return student age
       /  
      
      private byte inputAge() {
      System.out.print("Input student age: ");  
      while (true) {  
        try {  
          byte age = Byte.parseByte((scanner.nextLine()));  
          if (age < 0 && age > 100) {  
            throw new NumberFormatException();  
          }  
          return age;  
        } catch(NumberFormatException ex) {  
          System.out.print("invalid! Input student id again: ");  
        }  
      }  
      
      } /*
    • input student gpa
    • @return gpa
       */  
      
      private float inputGpa() {
      System.out.print("Input student gpa: ");  
      while (true) {  
        try {  
          float gpa = Float.parseFloat((scanner.nextLine()));  
          if (gpa < 0.0 && gpa > 10.0) {  
            throw new NumberFormatException();  
          }  
          return gpa;  
        } catch(NumberFormatException ex) {  
          System.out.print("invalid! Input student age again: ");  
        }  
      }  
      
      } // getter && setter public List < Student > getStudentList() {
      return studentList;  
      
      } public void setStudentList(List < Student > studentList) {
      this.studentList = studentList;  
      
      } }`

7. Tạo lớp Main.java

Lớp này chứa phương thức main(), định nghĩa menu.

`package vn.eLib; import java.util.Scanner; /

  • Main class
  • @author eLib.vn / public class Main { public static Scanner scanner = new Scanner(System. in ); public static void main(String[] args) {
    String choose = null;  
    boolean exit = false;  
    StudentManager studentManager = new StudentManager();  
    int studentId;  
    // show menu  
    showMenu();  
    while (true) {  
      choose = scanner.nextLine();  
      switch (choose) {  
      case "1":  
        studentManager.add();  
        break;  
      case "2":  
        studentId = studentManager.inputId();  
        studentManager.edit(studentId);  
        break;  
      case "3":  
        studentId = studentManager.inputId();  
        studentManager.delete(studentId);  
        break;  
      case "4":  
        studentManager.sortStudentByGPA();  
        break;  
      case "5":  
        studentManager.sortStudentByName();  
        break;  
      case "6":  
        studentManager.show();  
        break;  
      case "0":  
        System.out.println("exited!");  
        exit = true;  
        break;  
      default:  
        System.out.println("invalid! please choose action in below menu:");  
        break;  
      }  
      if (exit) {  
        break;  
      }  
      // show menu  
      showMenu();  
    }  
    
    } /*
    • create menu
       */  
      
      public static void showMenu() {
      System.out.println("---menu----");  
      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("0. exit.");  
      System.out.println("---");  
      System.out.print("Please choose: ");  
      
      } }`

8. Run bài tập quản lý sinh viên trong java

Kết quả:

`---menu----

  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. exit.

    Please choose: 1 student id = 1 Input student name: Vu Van Vinh Input student age: 22 Input student address: Ha Noi Input student gpa: 8

    ---menu----
  8. Add student.
  9. Edit student by id.
  10. Delete student by id.
  11. Sort student by gpa.
  12. Sort student by name.
  13. Show student.
  14. exit.

    Please choose: 1 student id = 2 Input student name: Pham Ba Hao Input student age: 21 Input student address: Vinh Phuc Input student gpa: 9

    ---menu----
  15. Add student.
  16. Edit student by id.
  17. Delete student by id.
  18. Sort student by gpa.
  19. Sort student by name.
  20. Show student.
  21. exit.
    Please choose: 6
    1 |          Vu Van Vinh |    22 |               Ha Noi |        8.0  
    2 |          Pham Ba Hao |    21 |            Vinh Phuc |        9.0  
    
    ---menu----
  22. Add student.
  23. Edit student by id.
  24. Delete student by id.
  25. Sort student by gpa.
  26. Sort student by name.
  27. Show student.
  28. exit.

    Please choose: 5

    ---menu----
  29. Add student.
  30. Edit student by id.
  31. Delete student by id.
  32. Sort student by gpa.
  33. Sort student by name.
  34. Show student.
  35. exit.
    Please choose: 6
    2 |          Pham Ba Hao |    21 |            Vinh Phuc |        9.0  
    1 |          Vu Van Vinh |    22 |               Ha Noi |        8.0  
    
    ---menu----
  36. Add student.
  37. Edit student by id.
  38. Delete student by id.
  39. Sort student by gpa.
  40. Sort student by name.
  41. Show student.
  42. exit.
    Please choose: 0 exited!`

Trên đây là bài tập Java quản lý sinh viên trong Java. Nếu bạn quan tâm bạn có thể mở rộng bài này bằng cách: dựng giao diện cho bài này bằng Swing, JavaFX hoặc JSP, Sử dụng cơ sở dữ liệu để lưu sinh viên, thêm chức năng tìm kiếm sinh viên. Chúc các bạn thành công!