Câu 1: OOP 1. Đề bài: Chương trình thực hiện các phép toán số học cơ bản import java.util.Scanner; // Interface IMathOperation interface IMathOperation { float PI = 3.1416f; void calculate(); void showInfo(); } // Addition class class Addition implements IMathOperation { private float operand1, operand2, result; public Addition(float operand1, float operand2) { this.operand1 = operand1; this.operand2 = operand2; } @Override public void calculate() { result = operand1 + operand2; } @Override public void showInfo() { calculate(); System.out.println("Lớp: Addition"); System.out.printf("%.2f + %.2f = %.2f%n", operand1, operand2, result); } } // Subtraction class class Subtraction implements IMathOperation { private float operand1, operand2, result; public Subtraction(float operand1, float operand2) { this.operand1 = operand1; this.operand2 = operand2; } @Override public void calculate() { result = operand1 - operand2; } @Override public void showInfo() { calculate(); System.out.println("Lớp: Subtraction"); System.out.printf("%.2f - %.2f = %.2f%n", operand1, operand2, result); } } // Multiplication class class Multiplication implements IMathOperation { private float operand1, operand2, result; public Multiplication(float operand1, float operand2) { this.operand1 = operand1; this.operand2 = operand2; } @Override public void calculate() { result = operand1 * operand2; } @Override public void showInfo() { calculate(); System.out.println("Lớp: Multiplication"); System.out.printf("%.2f * %.2f = %.2f%n", operand1, operand2, result); } } // Main class public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Addition input float a1 = sc.nextFloat(); float a2 = sc.nextFloat(); // Subtraction input float s1 = sc.nextFloat(); float s2 = sc.nextFloat(); // Multiplication input float m1 = sc.nextFloat(); float m2 = sc.nextFloat(); IMathOperation add = new Addition(a1, a2); IMathOperation sub = new Subtraction(s1, s2); IMathOperation mul = new Multiplication(m1, m2); add.showInfo(); sub.showInfo(); mul.showInfo(); sc.close(); } } 2. Đề bài: Quản lý sinh viên NEU import java.util.Scanner; // Interface IStaff interface IStaff { void work(); } // Interface IStudent interface IStudent { void study(); } // Abstract class Person abstract class Person { String name; // default private int age; // private protected String ID; // protected public String birthDate; // public public Person(String name, int age, String ID, String birthDate) { this.name = name; this.age = age; this.ID = ID; this.birthDate = birthDate; } // getter & setter for age public int getAge() { return age; } public void setAge(int age) { this.age = age; } // abstract method abstract void showInfo(); } // NEUStudent class class NEUStudent extends Person implements IStaff, IStudent { protected String studentID; public NEUStudent(String name, int age, String ID, String birthDate, String studentID) { super(name, age, ID, birthDate); this.studentID = studentID; } @Override void showInfo() { System.out.println("----- Thông tin sinh viên -----"); System.out.println("Tên: " + name); System.out.println("Tuổi: " + getAge()); System.out.println("ID: " + ID); System.out.println("Ngày sinh: " + birthDate); System.out.println("Mã sinh viên: " + studentID); } @Override public void work() { System.out.println(name + " đang làm việc tại khoa hoặc CLB..."); } @Override public void study() { System.out.println(name + " đang học tập chăm chỉ tại NEU..."); } } // Main class public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Student 1 String name1 = sc.nextLine(); int age1 = Integer.parseInt(sc.nextLine()); String id1 = sc.nextLine(); String birth1 = sc.nextLine(); String studentID1 = sc.nextLine(); // Student 2 String name2 = sc.nextLine(); int age2 = Integer.parseInt(sc.nextLine()); String id2 = sc.nextLine(); String birth2 = sc.nextLine(); String studentID2 = sc.nextLine(); NEUStudent s1 = new NEUStudent(name1, age1, id1, birth1, studentID1); NEUStudent s2 = new NEUStudent(name2, age2, id2, birth2, studentID2); s1.showInfo(); s1.work(); s1.study(); System.out.println(); s2.showInfo(); s2.work(); s2.study(); sc.close(); } } 3. Đề bài: Quản lý sản phẩm trong siêu thị mini import java.time.LocalDate; import java.util.Scanner; // a. Abstract class Product abstract class Product { private String name; // tên sản phẩm protected float price; // giá private String description; // mô tả protected int quantity; // số lượng public Product(String name, float price, String description, int quantity) { this.name = name; this.price = price; this.description = description; this.quantity = quantity; } // getter / setter public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } // abstract method abstract void showInfo(); } // b. Milk class class Milk extends Product { private LocalDate expirationDate; public Milk(String name, float price, String description, int quantity, LocalDate expirationDate) { super(name, price, description, quantity); this.expirationDate = expirationDate; } @Override void showInfo() { System.out.println("Tên sản phẩm: " + getName()); System.out.println("Mô tả: " + getDescription()); System.out.printf("Giá: %.2f%n", price); System.out.println("Số lượng: " + quantity); System.out.println("Ngày hết hạn: " + expirationDate); } // checkExpired public void checkExpired() { if (expirationDate.isBefore(LocalDate.now())) { System.out.println("Sản phẩm đã hết hạn."); } else { System.out.println("Sản phẩm vẫn còn hạn sử dụng."); } } } // c. Main public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); float price = Float.parseFloat(sc.nextLine()); String description = sc.nextLine(); int quantity = Integer.parseInt(sc.nextLine()); LocalDate expirationDate = LocalDate.parse(sc.nextLine()); Milk milk = new Milk(name, price, description, quantity, expirationDate); milk.showInfo(); milk.checkExpired(); sc.close(); } } 4. Đề bài: Quản lý động vật trong trang trại import java.util.Scanner; // Interface Animal interface Animal { void eat(); void showInfo(); } // Interface Bird extends Animal interface Bird extends Animal { void fly(); } // Interface Horse extends Animal interface Horse extends Animal { void run(); } // Pegasus class implements Bird & Horse class Pegasus implements Bird, Horse { public String name; private int age; // constructor public Pegasus(String name, int age) { this.name = name; this.age = age; } // getter & setter for age public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public void showInfo() { System.out.println("Tên: " + name); System.out.println("Tuổi: " + age); } @Override public void eat() { System.out.println(name + " đang ăn cỏ..."); } @Override public void fly() { System.out.println(name + " đang bay trên bầu trời..."); } @Override public void run() { System.out.println(name + " đang chạy rất nhanh..."); } } // Main class public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = Integer.parseInt(sc.nextLine()); Pegasus pegasus = new Pegasus(name, age); pegasus.showInfo(); pegasus.eat(); pegasus.fly(); pegasus.run(); sc.close(); } } 5. Đề bài: Chương trình quản lý nhân sự sử dụng lớp trừu tượng và kế thừa import java.time.LocalDate; import java.util.Scanner; // a. Abstract class Employee abstract class Employee { private String name; private LocalDate started; public Employee(String name, LocalDate started) { this.name = name; this.started = started; } // getter / setter public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalDate getStarted() { return started; } public void setStarted(LocalDate started) { this.started = started; } // abstract methods abstract void showInfo(); abstract double calcSalary(); } // b1. FullTimeEmployee class FullTimeEmployee extends Employee { private double monthlySalary; private double bonus; public FullTimeEmployee(String name, LocalDate started, double monthlySalary, double bonus) { super(name, started); this.monthlySalary = monthlySalary; this.bonus = bonus; } @Override double calcSalary() { return monthlySalary + bonus; } @Override void showInfo() { System.out.println("=== Nhân viên Full-Time ==="); System.out.println("Tên: " + getName()); System.out.println("Ngày bắt đầu: " + getStarted()); System.out.printf("Lương cơ bản: %.2f%n", monthlySalary); System.out.printf("Thưởng: %.2f%n", bonus); System.out.printf("Lương thực nhận: %.2f%n", calcSalary()); System.out.println(); } } // b2. PartTimeEmployee class PartTimeEmployee extends Employee { private int workingHour; private double rate; public PartTimeEmployee(String name, LocalDate started, int workingHour, double rate) { super(name, started); this.workingHour = workingHour; this.rate = rate; } @Override double calcSalary() { return workingHour * rate; } @Override void showInfo() { System.out.println("=== Nhân viên Part-Time ==="); System.out.println("Tên: " + getName()); System.out.println("Ngày bắt đầu: " + getStarted()); System.out.println("Số giờ làm: " + workingHour); System.out.printf("Đơn giá/giờ: %.2f%n", rate); System.out.printf("Lương thực nhận: %.2f%n", calcSalary()); } } // c. Main public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // FullTimeEmployee input String ftName = sc.nextLine(); LocalDate ftStarted = LocalDate.parse(sc.nextLine()); double monthlySalary = Double.parseDouble(sc.nextLine()); double bonus = Double.parseDouble(sc.nextLine()); // PartTimeEmployee input String ptName = sc.nextLine(); LocalDate ptStarted = LocalDate.parse(sc.nextLine()); int workingHour = Integer.parseInt(sc.nextLine()); double rate = Double.parseDouble(sc.nextLine()); Employee fullTime = new FullTimeEmployee( ftName, ftStarted, monthlySalary, bonus); Employee partTime = new PartTimeEmployee( ptName, ptStarted, workingHour, rate); // đa hình fullTime.showInfo(); partTime.showInfo(); sc.close(); } } 6. Đề bài: Quản lý động vật trong sở thú bằng kế thừa và lớp trừu tượng import java.util.Scanner; // Abstract class Animal abstract class Animal { protected int age; protected String gender; public Animal(int age, String gender) { this.age = age; this.gender = gender; } // mặc định không phải động vật có vú public boolean isMammal() { return false; } // abstract method abstract void showInfo(); } // Duck class class Duck extends Animal { public String color; public Duck(int age, String gender, String color) { super(age, gender); this.color = color; } public void swim() { System.out.println("Vịt đang bơi..."); } public void quack() { System.out.println("Vịt kêu: Quack Quack!"); } @Override void showInfo() { System.out.println("=== Thông Tin Vịt ==="); System.out.println("Tuổi: " + age); System.out.println("Giới tính: " + gender); System.out.println("Màu sắc: " + color); System.out.println("Có phải động vật có vú? " + isMammal()); } } // Fish class class Fish extends Animal { private int size; private boolean canEat; public Fish(int age, String gender, int size, boolean canEat) { super(age, gender); this.size = size; this.canEat = canEat; } public void swim() { System.out.println("Cá đang bơi..."); } @Override void showInfo() { System.out.println("=== Thông Tin Cá ==="); System.out.println("Tuổi: " + age); System.out.println("Giới tính: " + gender); System.out.println("Kích thước: " + size); System.out.println("Có thể ăn động vật khác? " + canEat); System.out.println("Có phải động vật có vú? " + isMammal()); } } // Horse class class Horse extends Animal { private boolean isWild; public Horse(int age, String gender, boolean isWild) { super(age, gender); this.isWild = isWild; } public void run() { System.out.println("Ngựa đang chạy..."); } @Override public boolean isMammal() { return true; } @Override void showInfo() { System.out.println("=== Thông Tin Ngựa ==="); System.out.println("Tuổi: " + age); System.out.println("Giới tính: " + gender); System.out.println("Hoang dã: " + isWild); System.out.println("Có phải động vật có vú? " + isMammal()); } } // Main class public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Duck input int duckAge = sc.nextInt(); String duckGender = sc.next(); String duckColor = sc.next(); // Fish input int fishAge = sc.nextInt(); String fishGender = sc.next(); int fishSize = sc.nextInt(); boolean canEat = sc.nextBoolean(); // Horse input int horseAge = sc.nextInt(); String horseGender = sc.next(); boolean isWild = sc.nextBoolean(); Duck duck = new Duck(duckAge, duckGender, duckColor); Fish fish = new Fish(fishAge, fishGender, fishSize, canEat); Horse horse = new Horse(horseAge, horseGender, isWild); duck.showInfo(); duck.swim(); duck.quack(); System.out.println(); fish.showInfo(); fish.swim(); System.out.println(); horse.showInfo(); horse.run(); sc.close(); } } 7. Đề bài: Chương trình tính toán hình học với Interface và các lớp triển khai import java.util.Scanner; // Interface IShape interface IShape { float PI = 3.1416f; float getArea(); float getPerimeter(); void showInfo(); } // Circle class class Circle implements IShape { private float radius; public Circle(float radius) { this.radius = radius; } public float getRadius() { return radius; } public void setRadius(float radius) { this.radius = radius; } @Override public float getArea() { return PI * radius * radius; } @Override public float getPerimeter() { return 2 * PI * radius; } @Override public void showInfo() { System.out.printf( "Hình tròn: diện tích %.2f, chu vi %.2f%n", getArea(), getPerimeter() ); } } // Rectangle class class Rectangle implements IShape { private double width; private double length; public Rectangle(double width, double length) { this.width = width; this.length = length; } @Override public float getArea() { return (float) (width * length); } @Override public float getPerimeter() { return (float) (2 * (width + length)); } @Override public void showInfo() { System.out.printf( "Hình chữ nhật: diện tích %.2f, chu vi %.2f%n", getArea(), getPerimeter() ); } } // Main class public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); float radius = sc.nextFloat(); double width = sc.nextDouble(); double length = sc.nextDouble(); IShape circle = new Circle(radius); IShape rectangle = new Rectangle(width, length); circle.showInfo(); rectangle.showInfo(); sc.close(); } } 8. Đề bài: Quản lý tài khoản ngân hàng với lớp trừu tượng và đa hình import java.util.Scanner; /* ===== LỚP TRỪU TƯỢNG ===== */ abstract class BankAccount { private String ownerName; protected double balance; public BankAccount(String ownerName, double balance) { this.ownerName = ownerName; this.balance = balance; } public String getOwnerName() { return ownerName; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public abstract double calcInterest(); public abstract void showInfo(); } /* ===== TÀI KHOẢN TIẾT KIỆM ===== */ class SavingAccount extends BankAccount { private double interestRate; public SavingAccount(String ownerName, double balance, double interestRate) { super(ownerName, balance); this.interestRate = interestRate; } @Override public double calcInterest() { return balance * interestRate / 100; } @Override public void showInfo() { System.out.println("=== Tài khoản Tiết kiệm ==="); System.out.println("Chủ tài khoản: " + getOwnerName()); System.out.printf("Số dư: %.2f\n", balance); System.out.printf("Lãi: %.2f\n", calcInterest()); } } /* ===== TÀI KHOẢN THANH TOÁN ===== */ class CheckingAccount extends BankAccount { private double fee; public CheckingAccount(String ownerName, double balance, double fee) { super(ownerName, balance); this.fee = fee; } @Override public double calcInterest() { return 0; } @Override public void showInfo() { System.out.println("=== Tài khoản Thanh toán ==="); System.out.println("Chủ tài khoản: " + getOwnerName()); System.out.printf("Số dư: %.2f\n", balance); System.out.printf("Phí duy trì: %.2f\n", fee); } } /* ===== MAIN ===== */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // SavingAccount String saveName = sc.nextLine(); double saveBalance = sc.nextDouble(); double interestRate = sc.nextDouble(); sc.nextLine(); BankAccount saving = new SavingAccount(saveName, saveBalance, interestRate); // CheckingAccount String checkName = sc.nextLine(); double checkBalance = sc.nextDouble(); double fee = sc.nextDouble(); BankAccount checking = new CheckingAccount(checkName, checkBalance, fee); // Output saving.showInfo(); checking.showInfo(); } } 9. Đề bài: Hệ thống quản lý khóa học và giảng viên import java.util.Scanner; /* ===== INTERFACE ===== */ interface ITeacher { void teach(); void showTeacherInfo(); } /* ===== ABSTRACT CLASS ===== */ abstract class Course { protected String courseName; protected int duration; public Course(String courseName, int duration) { this.courseName = courseName; this.duration = duration; } public abstract void showCourseInfo(); } /* ===== ONLINE COURSE ===== */ class OnlineCourse extends Course { private String platform; public OnlineCourse(String courseName, int duration, String platform) { super(courseName, duration); this.platform = platform; } @Override public void showCourseInfo() { System.out.println("=== Thông tin Khóa học Online ==="); System.out.println("Tên khóa học: " + courseName); System.out.println("Số buổi: " + duration); System.out.println("Nền tảng: " + platform); } } /* ===== LECTURER ===== */ class Lecturer implements ITeacher { private String name; private String level; public Lecturer(String name, String level) { this.name = name; this.level = level; } @Override public void showTeacherInfo() { System.out.println("=== Thông tin Giảng viên ==="); System.out.println("Họ tên: " + name); System.out.println("Trình độ: " + level); } @Override public void teach() { System.out.println(name + " đang bắt đầu giảng dạy..."); } } /* ===== MAIN ===== */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String lecturerName = sc.nextLine(); String level = sc.nextLine(); String courseName = sc.nextLine(); int duration = sc.nextInt(); sc.nextLine(); // clear buffer String platform = sc.nextLine(); Lecturer lecturer = new Lecturer(lecturerName, level); Course course = new OnlineCourse(courseName, duration, platform); lecturer.showTeacherInfo(); lecturer.teach(); course.showCourseInfo(); } } Câu 2: File I/O đủ 1. Đề bài: Ghi và đọc đối tượng Sinh viên bằng ObjectOutputStream và ObjectInputStream import java.io.*; import java.util.Scanner; /* ===== STUDENT ===== */ class Student implements Serializable { private String name; private int age; private double score; public Student(String name, int age, double score) { this.name = name; this.age = age; this.score = score; } public String getName() { return name; } public int getAge() { return age; } public double getScore() { return score; } } /* ===== MAIN ===== */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = sc.nextInt(); double score = sc.nextDouble(); Student student = new Student(name, age, score); // Ghi object vào file try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"))) { oos.writeObject(student); } catch (IOException e) { return; } // Đọc object từ file try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.txt"))) { Student s = (Student) ois.readObject(); System.out.println("Name: " + s.getName()); System.out.println("Age: " + s.getAge()); System.out.printf("Score: %.2f", s.getScore()); } catch (IOException | ClassNotFoundException e) { return; } } } 2. Đề bài: Ghi và đọc đối tượng bằng ObjectOutputStream và ObjectInputStream import java.io.*; import java.util.Scanner; /* ===== MYOBJECT ===== */ class MyObject implements Serializable { private String message; private int value; public MyObject(String message, int value) { this.message = message; this.value = value; } @Override public String toString() { return "MyObject{message='" + message + "', value=" + value + "}"; } } /* ===== MAIN ===== */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String message = sc.nextLine(); int value = sc.nextInt(); MyObject obj = new MyObject(message, value); // Ghi object vào file try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt"))) { oos.writeObject(obj); } catch (IOException e) { return; } // Đọc object từ file và in ra try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"))) { MyObject readObj = (MyObject) ois.readObject(); System.out.println(readObj); // tự động gọi toString() } catch (IOException | ClassNotFoundException e) { return; } } } 3. Đề bài: Ghi và đọc file văn bản bằng FileWriter và BufferedReader import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { List lines = new ArrayList<>(); // Đọc toàn bộ dòng từ bàn phím (đến EOF) try (BufferedReader br = new BufferedReader( new InputStreamReader(System.in))) { String line; while ((line = br.readLine()) != null && !line.isEmpty()) { lines.add(line); } } catch (IOException e) { return; } // Ghi vào file text.txt try (FileWriter fw = new FileWriter("text.txt")) { for (String s : lines) { fw.write(s + System.lineSeparator()); } } catch (IOException e) { return; } // Đọc lại file và in ra + đếm số dòng int count = 0; try (BufferedReader br = new BufferedReader( new FileReader("text.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); count++; } } catch (IOException e) { return; } System.out.println("số dòng: " + count); } } 4. Đề bài: Quản lý danh sách sinh viên bằng OutputStreamWriter và InputStreamReader import java.io.*; import java.util.*; public class Main { // Hàm chuẩn hóa họ tên private static String normalizeName(String name) { name = name.trim().toLowerCase(); String[] parts = name.split("\\s+"); StringBuilder sb = new StringBuilder(); for (String p : parts) { sb.append(Character.toUpperCase(p.charAt(0))) .append(p.substring(1)) .append(" "); } return sb.toString().trim(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); List students = new ArrayList<>(); // Nhập danh sách sinh viên (dừng khi gặp dòng trống) while (true) { String line = sc.nextLine(); if (line.trim().isEmpty()) break; students.add(normalizeName(line)); } // Ghi vào file students.txt (UTF-8) try (OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("students.txt"), "UTF-8")) { for (String s : students) { writer.write(s + "\n"); } writer.write("Số lượng sinh viên: " + students.size()); } catch (IOException e) { return; } // Đọc lại file và in ra màn hình try (InputStreamReader reader = new InputStreamReader( new FileInputStream("students.txt"), "UTF-8")) { int ch; while ((ch = reader.read()) != -1) { System.out.print((char) ch); } } catch (IOException e) { return; } } } 5. Đề bài: Xử lý chuỗi đọc từ file: chữ ở vị trí lẻ chuyển thành chữ hoa import java.io.*; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.nextLine(); // Ghi chuỗi vào file raw.txt try (FileWriter fw = new FileWriter("raw.txt")) { fw.write(input); } catch (IOException e) { return; } // Đọc file và xử lý chuỗi StringBuilder result = new StringBuilder(); try (FileReader fr = new FileReader("raw.txt")) { int ch; int index = 0; while ((ch = fr.read()) != -1) { char c = (char) ch; if (index % 2 == 1) { result.append(Character.toUpperCase(c)); } else { result.append(Character.toLowerCase(c)); } index++; } } catch (IOException e) { return; } // In kết quả System.out.print(result.toString()); } } 6. Đề bài: Ghi và đọc tên tiếng Việt bằng BufferedWriter/BufferedReader (Xử lý UTF-8) import java.io.*; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); // ===== GHI FILE UTF-8 ===== try (BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream("utf8.txt"), "UTF-8"))) { bw.write(name); } catch (IOException e) { return; } // ===== ĐỌC FILE + XỬ LÝ ===== try (BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream("utf8.txt"), "UTF-8"))) { String line = br.readLine(); if (line != null) { String[] parts = line.trim().split("\\s+"); // Viết hoa họ (từ đầu tiên) parts[0] = parts[0].toUpperCase(); // Ghép lại chuỗi StringBuilder result = new StringBuilder(); for (String p : parts) { result.append(p).append(" "); } System.out.print(result.toString().trim()); } } catch (IOException e) { return; } } } 7. Đề bài: Ghi và đọc dữ liệu nhị phân với DataOutputStream và DataInputStream import java.io.*; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] nums = new int[4]; // Nhập 4 số nguyên for (int i = 0; i < 4; i++) { nums[i] = sc.nextInt(); } // Ghi 4 số nguyên vào file int.txt try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("int.txt"))) { for (int x : nums) { dos.writeInt(x); } } catch (IOException e) { return; } // Đọc lại 4 số nguyên và tính tổng int sum = 0; try (DataInputStream dis = new DataInputStream(new FileInputStream("int.txt"))) { for (int i = 0; i < 4; i++) { sum += dis.readInt(); } } catch (IOException e) { return; } // In kết quả System.out.println("Tổng của các số nguyên là: " + sum); } } CÂU 3: THREAD 1. Tỉnh tổng một mảng số nguyên lớn bằng đa luồng import java.util.*; class SumThread extends Thread { private int[] arr; private int start; private int end; private long partialSum; public SumThread (int[] arr, int start, int end){ this.arr = arr; this.start = start; this.end = end; } public long getpartialSum(){ return partialSum; } public void run(){ long s = 0; for (int i = start; i < end; i++){ s += arr[i]; } partialSum = s; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[] arr = new int[N]; for (int i = 0; i < N; i++) arr[i] = sc.nextInt(); int K = sc.nextInt(); SumThread[] threads = new SumThread[K]; int chunk = N/K; for(int i = 0; i < K; i++){ int start = i*chunk; int end = (i == K-1) ? N : (i+1)* chunk; threads[i] = new SumThread(arr, start, end); threads[i].start(); } long total = 0; for( int i = 0; i Maxvalue){ Maxvalue = arr[i]; } } Max = Maxvalue; } int globalMax = Integer.MIN_VALUE; for (int i = 0; i< K; i++){ try{ threads[i].join(); int local = threads[i].getMax(); if (local > globalMax){ globalMax = local; } } 3. Đếm số lượng số nguyên tố bằng đa luồng private boolean isPrime(int x){ if(x <2) return false; if (x == 2) return true; if(x % 2 == 0) return false; for (int i = 3; i*i <= x;i+=2){ if (x%i==0){ return false; } } return true; } public void run(){ int s = 0; for (int i = start; i < end; i++){ if(isPrime(arr[i])){ s++; } } SumPrime = s; } } 4. Tính tổng bình phương các số lớn bằng đa luồng 5. Đếm số lần xuất hiện X trong mảng lớn 6. Tính tổng giai thừa các số trong mảng // tính giai thừa private long factorial(int x) { long f = 1; for (int i = 1; i <= x; i++) { f *= i; } return f; } public long getPartialSum() { return partialSum; } @Override public void run() { long s = 0; for (int i = start; i < end; i++) { if (arr[i] >= 0) { // giả sử chỉ tính giai thừa số không âm s += factorial(arr[i]); } } partialSum = s; } } 7. Tính tổng tất cả các ước số của các phần tử trong mảng lớn // tính tổng các ước số dương của n private long sumOfDivisors(int n) { if (n <= 0) return 0; long sum = 0; int limit = (int) Math.sqrt(n); for (int i = 1; i <= limit; i++) { if (n % i == 0) { sum += i; int other = n / i; if (other != i) { sum += other; } } } return sum; } public long getPartialSum() { return partialSum; } @Override public void run() { long s = 0; for (int i = start; i < end; i++) { s += sumOfDivisors(arr[i]); } partialSum = s; } } Câu 4: Framework 1. Đề bài: Xếp hạng theo điểm số (tự động sắp xếp) import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); Map map = new HashMap<>(); // Nhập dữ liệu for (int i = 0; i < N; i++) { String name = sc.next(); int score = sc.nextInt(); map.put(name, score); } // TreeSet với Comparator: điểm giảm dần, nếu bằng thì theo tên TreeSet ranking = new TreeSet<>( (a, b) -> { int cmp = map.get(b) - map.get(a); // giảm dần theo điểm if (cmp == 0) { return a.compareTo(b); // cùng điểm → theo tên } return cmp; } ); ranking.addAll(map.keySet()); // In kết quả for (String name : ranking) { System.out.println(name + ": " + map.get(name)); } } } 2. Đề bài: So sánh hai tập hợp và xuất phần tử chung import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Tập A - HashSet int N = sc.nextInt(); Set setA = new HashSet<>(); for (int i = 0; i < N; i++) { setA.add(sc.nextInt()); } // Tập B - TreeSet int M = sc.nextInt(); Set setB = new TreeSet<>(); for (int i = 0; i < M; i++) { setB.add(sc.nextInt()); } // Giao của A và B (giữ thứ tự tăng dần nhờ TreeSet) setB.retainAll(setA); // In kết quả for (int x : setB) { System.out.print(x + " "); } } } 3. Đề bài: Đếm ký tự và sắp xếp theo bảng chữ cái import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); // Lưu từng ký tự vào LinkedList LinkedList list = new LinkedList<>(); for (char c : s.toCharArray()) { list.add(c); } // Đếm và tự động sắp xếp bằng TreeMap TreeMap countMap = new TreeMap<>(); for (char c : list) { countMap.put(c, countMap.getOrDefault(c, 0) + 1); } // In kết quả for (Map.Entry entry : countMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } 4. Đề bài: Đếm số lần xuất hiện của từng phần tử import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); ArrayList list = new ArrayList<>(); for (int i = 0; i < N; i++) { list.add(sc.nextInt()); } // HashMap đếm số lần HashMap countMap = new HashMap<>(); // Lưu thứ tự xuất hiện lần đầu ArrayList order = new ArrayList<>(); for (int x : list) { if (!countMap.containsKey(x)) { countMap.put(x, 1); order.add(x); } else { countMap.put(x, countMap.get(x) + 1); } } // In theo thứ tự xuất hiện lần đầu for (int x : order) { System.out.println(x + ": " + countMap.get(x)); } } } 5. Đề bài: Trích lọc phần tử duy nhất và sắp xếp tăng dần import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); // Lưu danh sách số nguyên ArrayList list = new ArrayList<>(); for (int i = 0; i < N; i++) { list.add(sc.nextInt()); } // HashMap để đếm số lần xuất hiện HashMap countMap = new HashMap<>(); // Lưu thứ tự xuất hiện lần đầu ArrayList order = new ArrayList<>(); for (int x : list) { if (!countMap.containsKey(x)) { countMap.put(x, 1); order.add(x); // ghi nhận lần xuất hiện đầu } else { countMap.put(x, countMap.get(x) + 1); } } // In kết quả theo thứ tự xuất hiện lần đầu for (int x : order) { System.out.println(x + ": " + countMap.get(x)); } } } 6. Đề bài: Loại bỏ phần tử trùng lặp và sắp xếp theo thứ tự xuất hiện import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); // Lưu danh sách ban đầu ArrayList list = new ArrayList<>(); for (int i = 0; i < N; i++) { list.add(sc.nextInt()); } // HashSet để kiểm tra trùng HashSet seen = new HashSet<>(); ArrayList result = new ArrayList<>(); // Loại trùng nhưng giữ thứ tự xuất hiện for (int x : list) { if (!seen.contains(x)) { seen.add(x); result.add(x); } } // In kết quả for (int x : result) { System.out.print(x + " "); } } } 7. Đề bài: Quản lý danh sách sinh viên bằng ArrayList có sử dụng Generics import java.util.*; class Student { private String name; private int age; private double score; public Student(String name, int age, double score) { this.name = name; this.age = age; this.score = score; } public String getName() { return name; } public int getAge() { return age; } public double getScore() { return score; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); ArrayList list = new ArrayList<>(); // Nhập danh sách sinh viên for (int i = 0; i < N; i++) { String name = sc.next(); int age = sc.nextInt(); double score = sc.nextDouble(); list.add(new Student(name, age, score)); } // Tìm sinh viên có điểm cao nhất (giữ người xuất hiện đầu tiên) Student best = list.get(0); for (Student s : list) { if (s.getScore() > best.getScore()) { best = s; } } // In kết quả (đúng format) System.out.println("Name: " + best.getName()); System.out.println(); System.out.println("Age: " + best.getAge()); System.out.println(); System.out.printf("Score: %.2f", best.getScore()); } } Câu 5: Streams 1. Đề bài: Phân loại mức tiêu thụ điện của hộ dân import java.util.*; import java.util.function.*; import java.util.stream.*; class Home { String owner; double kwh; Home(String owner, double kwh) { this.owner = owner; this.kwh = kwh; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.nextLine()); List list = new ArrayList<>(); for (int i = 0; i < N; i++) { String[] p = sc.nextLine().split(" "); list.add(new Home(p[0], Double.parseDouble(p[1]))); } // Predicate: lọc hộ có kWh >= 50 Predicate highUsage = h -> h.kwh >= 50; // Function: tính tiền điện Function calcMoney = h -> h.kwh * 3500; // Comparator: sắp xếp theo tiền giảm dần Comparator byMoneyDesc = (a, b) -> Double.compare(calcMoney.apply(b), calcMoney.apply(a)); // Consumer: in kết quả Consumer printer = h -> System.out.printf("%s %.2f %.2f%n", h.owner, h.kwh, calcMoney.apply(h)); // Xử lý bằng Stream list.stream() .filter(highUsage) .sorted(byMoneyDesc) .forEach(printer); } } 2. Đề bài: Thống kê chi tiêu của khách hàng import java.util.*; import java.util.function.*; import java.util.stream.*; class Transaction { String name; double amount; Transaction(String name, double amount) { this.name = name; this.amount = amount; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.nextLine()); List list = new ArrayList<>(); for (int i = 0; i < N; i++) { String[] p = sc.nextLine().split(" "); list.add(new Transaction(p[0], Double.parseDouble(p[1]))); } // Predicate: lọc giao dịch >= 100000 Predicate validAmount = t -> t.amount >= 100000; // Function: Transaction -> "Tên: số_tiền" Function toStringFunc = t -> t.name + ": " + String.format("%.2f", t.amount); // BinaryOperator: chọn chuỗi có số tiền lớn hơn (cùng tên) BinaryOperator maxAmount = (t1, t2) -> t1.amount >= t2.amount ? t1 : t2; // Consumer: in kết quả Consumer printer = System.out::println; // Xử lý Stream list.stream() .filter(validAmount) .collect(Collectors.toMap( t -> t.name, // key: tên t -> t, // value: Transaction maxAmount, // cùng tên -> lấy số tiền lớn hơn LinkedHashMap::new // giữ thứ tự xuất hiện )) .values().stream() .map(toStringFunc) .forEach(printer); } } 3. Đề bài: Quản lý điểm danh nhân viên import java.util.*; import java.util.function.*; import java.util.stream.*; class Employee { String name; double hours; Employee(String name, double hours) { this.name = name; this.hours = hours; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.nextLine()); List input = new ArrayList<>(); for (int i = 0; i < N; i++) { String[] p = sc.nextLine().split(" "); input.add(new Employee(p[0], Double.parseDouble(p[1]))); } // Supplier: cung cấp danh sách nhân viên Supplier> supplier = () -> input; // Predicate: lọc nhân viên làm >= 6 giờ Predicate enoughHours = e -> e.hours >= 6; // Function: đổi giờ -> phút Function toMinutes = e -> (int) (e.hours * 60); // Comparator: sắp xếp theo phút giảm dần Comparator byMinutesDesc = (a, b) -> Integer.compare( toMinutes.apply(b), toMinutes.apply(a) ); // Xử lý và in kết quả supplier.get().stream() .filter(enoughHours) .sorted(byMinutesDesc) .forEach(e -> System.out.printf( "%s %.2f %d%n", e.name, e.hours, toMinutes.apply(e) ) ); } } 4. Đề bài: Xử lý danh sách khách hàng và tính phí dịch vụ import java.util.*; import java.util.function.*; import java.util.stream.*; class Customer { String name; int times; Customer(String name, int times) { this.name = name; this.times = times; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.nextLine()); List list = new ArrayList<>(); for (int i = 0; i < N; i++) { String[] p = sc.nextLine().split(" "); list.add(new Customer(p[0], Integer.parseInt(p[1]))); } // Predicate: lọc khách hàng có số lần >= 3 Predicate validCustomer = c -> c.times >= 3; // Function: tính phí dịch vụ Function calcFee = c -> c.times * 15000.0; // Comparator: sắp xếp theo phí giảm dần Comparator byFeeDesc = (a, b) -> Double.compare( calcFee.apply(b), calcFee.apply(a) ); // Consumer: in kết quả Consumer printer = c -> System.out.printf( "%s %d %.2f%n", c.name, c.times, calcFee.apply(c) ); // Xử lý bằng Stream list.stream() .filter(validCustomer) .sorted(byFeeDesc) .forEach(printer); } } 5. Đề bài: Lọc – chuyển đổi – sắp xếp danh sách đơn hàng import java.util.*; import java.util.function.*; import java.util.stream.*; class Order { String code; double total; Order(String code, double total) { this.code = code; this.total = total; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.nextLine()); List input = new ArrayList<>(); for (int i = 0; i < N; i++) { String[] p = sc.nextLine().split(" "); input.add(new Order(p[0], Double.parseDouble(p[1]))); } // Supplier: trả về danh sách đơn hàng Supplier> supplier = () -> input; // Predicate: lọc đơn có tổng tiền >= 500 Predicate validOrder = o -> o.total >= 500; // Function: chuyển mã đơn -> "ORDER-" Function formatCode = o -> "ORDER-" + o.code; // Comparator: sắp xếp theo tổng tiền giảm dần Comparator byTotalDesc = (a, b) -> Double.compare(b.total, a.total); // Xử lý và in kết quả supplier.get().stream() .filter(validOrder) .sorted(byTotalDesc) .forEach(o -> System.out.printf( "%s %.2f%n", formatCode.apply(o), o.total ) ); } } 6. Đề bài: Phân loại nhân viên theo nhóm tuổi import java.util.*; import java.util.function.*; import java.util.stream.*; class Employee { String name; int age; Employee(String name, int age) { this.name = name; this.age = age; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.nextLine()); List list = new ArrayList<>(); for (int i = 0; i < N; i++) { String[] p = sc.nextLine().split(" "); list.add(new Employee(p[0], Integer.parseInt(p[1]))); } // Predicate: lọc nhân viên tuổi >= 25 Predicate ageFilter = e -> e.age >= 25; // Function: ánh xạ Employee -> "Tên - Tuổi" Function toStringFn = e -> e.name + " - " + e.age; // BinaryOperator: khi trùng tên -> chọn chuỗi có độ dài lớn hơn BinaryOperator chooseLongerString = (e1, e2) -> { String s1 = toStringFn.apply(e1); String s2 = toStringFn.apply(e2); return s1.length() >= s2.length() ? e1 : e2; }; // Comparator: sắp xếp giảm dần theo tuổi Comparator byAgeDesc = (a, b) -> Integer.compare(b.age, a.age); // Xử lý Streams list.stream() .filter(ageFilter) .collect(Collectors.toMap( e -> e.name, // key: tên e -> e, // value: Employee chooseLongerString, // xung đột -> BinaryOperator LinkedHashMap::new // giữ thứ tự xuất hiện )) .values().stream() .sorted(byAgeDesc) .map(toStringFn) .forEach(System.out::println); } } 7. Đề bài: Lọc và xử lý danh sách sản phẩm import java.util.*; import java.util.function.*; import java.util.stream.*; class Product { String name; double price; Product(String name, double price) { this.name = name; this.price = price; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.nextLine()); List input = new ArrayList<>(); for (int i = 0; i < N; i++) { String[] p = sc.nextLine().split(" "); input.add(new Product(p[0], Double.parseDouble(p[1]))); } // Supplier: cung cấp danh sách sản phẩm Supplier> supplier = () -> input; // Predicate: lọc sản phẩm có giá >= 100 Predicate priceFilter = p -> p.price >= 100; // Function: chuyển tên sản phẩm thành chữ in hoa Function toUpperName = p -> p.name.toUpperCase(); // Comparator: sắp xếp tăng dần theo giá Comparator byPriceAsc = (a, b) -> Double.compare(a.price, b.price); // Consumer: in kết quả Consumer printer = p -> System.out.printf("%s %.2f%n", toUpperName.apply(p), p.price); // Xử lý bằng Stream supplier.get().stream() .filter(priceFilter) .sorted(byPriceAsc) .forEach(printer); } }