import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class LibraryBorrowingService {
    public static void processBorrowingRequest(String[] args) {
        if (args.length != 4) {
            System.out.println("输入格式错误，请按照以下格式输入：图书ID 借阅者姓名 借阅日期 预计归还日期");
            return;
        }
        String bookId = args[0];
        String borrowerName = args[1];
        String borrowDateStr = args[2];
        String returnDateStr = args[3];
        LocalDate borrowDate;
        LocalDate returnDate;
        try {
            borrowDate = LocalDate.parse(borrowDateStr, DateTimeFormatter.ISO_LOCAL_DATE);
            returnDate = LocalDate.parse(returnDateStr, DateTimeFormatter.ISO_LOCAL_DATE);
        } catch (DateTimeParseException e) {
            System.out.println("日期格式错误，请使用YYYY-MM-DD格式。");
            return;
        }
        if (!returnDate.isAfter(borrowDate)) {
            System.out.println("预计归还日期应该在借阅日期之后。");
            return;
        }
        System.out.println("图书借阅成功。图书ID: " + bookId + ", 借阅者: " + borrowerName + ", 借阅日期: " + borrowDateStr + ", 预计归还日期: " + returnDateStr);
    }
    public static void main(String[] args) {
        String[] testData = {"1234", "张三", "2023-04-01", "2023-04-15"};
        processBorrowingRequest(testData);
    }
}

Please design a Java program to handle the borrowing of books in a library. The program should be able to accept a string array as a parameter, which contains the book ID, borrower's name, borrowing date, and expected return date. If the input parameters do not meet the requirements (i.e., the number of parameters is not 4), the program should prompt the user that the input format is incorrect and provide a correct format example. If the input is correct, the program should check the validity of the borrowing date and the expected return date (the expected return date should be after the borrowing date). If the dates are invalid, the program should prompt the user and terminate. If everything is fine, the program should confirm the book borrowing success. Please design a simple method to verify the validity of dates yourself.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class LibraryBorrowingService {
    public static void processBorrowingRequest(String[] args) {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.time.LocalDate;
public class LibraryBorrowingServiceTest {
    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final PrintStream originalOut = System.out;
    @BeforeEach
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
    }
    @org.junit.jupiter.api.AfterEach
    public void restoreStreams() {
        System.setOut(originalOut);
    }
    @Test
    public void testCorrectInput() {
        String[] testData = {"1234", "张三", "2023-04-01", "2023-04-15"};
        LibraryBorrowingService.processBorrowingRequest(testData);
        assertTrue(outContent.toString().contains("图书借阅成功"));
    }
    @Test
    public void testIncorrectInputLength() {
        String[] testData = {"1234", "张三", "2023-04-01"};
        LibraryBorrowingService.processBorrowingRequest(testData);
        assertTrue(outContent.toString().contains("输入格式错误"));
    }
    @Test
    public void testInvalidDateFormat() {
        String[] testData = {"1234", "张三", "2023-04-01", "2023/04/15"};
        LibraryBorrowingService.processBorrowingRequest(testData);
        assertTrue(outContent.toString().contains("日期格式错误"));
    }
    @Test
    public void testReturnDateBeforeBorrowDate() {
        String[] testData = {"1234", "张三", "2023-04-15", "2023-04-01"};
        LibraryBorrowingService.processBorrowingRequest(testData);
        assertTrue(outContent.toString().contains("预计归还日期应该在借阅日期之后"));
    }
    @Test
    public void testBorrowDateEqualsReturnDate() {
        String[] testData = {"1234", "张三", "2023-04-15", "2023-04-15"};
        LibraryBorrowingService.processBorrowingRequest(testData);
        assertTrue(outContent.toString().contains("预计归还日期应该在借阅日期之后"));
    }
}


import java.awt.Color;
public class ImmutableCircle {
    private final Color color;
    public ImmutableCircle(Color color) {
        this.color = color;
    }
    public void changeColor(Color newColor) {
        throw new UnsupportedOperationException("圆形是不可变的，不能改变颜色");
    }
    public Color getColor() {
        return color;
    }
}
class CheckImmutableCircle {
    public static void main(String[] args) {
        ImmutableCircle circle = new ImmutableCircle(Color.RED);
        try {
            circle.changeColor(Color.BLUE);
            System.out.println("错误：不应该能够改变颜色");
        } catch (UnsupportedOperationException e) {
            System.out.println("正确：抛出了不支持操作的异常，因为圆形是不可变的");
        }
        if (circle.getColor().equals(Color.RED)) {
            System.out.println("正确：圆形的颜色没有改变");
        } else {
            System.out.println("错误：圆形的颜色不应该改变");
        }
    }
}

Please write a Java class `ImmutableCircle` that represents an immutable circle. The class should include a method `changeColor(Color newColor)` that attempts to change the color of the circle. However, since the circle is immutable, this method should throw an exception, indicating to the user that this object is read-only and its color cannot be changed. Ensure your code includes the necessary import statements.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.awt.Color;
public class ImmutableCircle {
    private final Color color;
    public ImmutableCircle(Color color) {
    }
    public void changeColor(Color newColor) {
    }
    public Color getColor() {
    }
}
```

Question: Write a piece of python code to achieve the following function.
Find the maximum perfect square number that is less than the nth Fibonacci number.
The function's name is max_square_number, and the input is an integer n.

Answer:
```python
def max_square_number(n):
 if n <= 2:
 return 0 # For the first two numbers in the Fibonacci sequence, no complete square numbers can be used.

 fibs = [0, 1] # Store the first two numbers of the Fibonacci sequence
 squares = [] # Store the list of perfect square numbers

 max_square = 0
 i = 2

 while i <= n:
 fibs.append(fibs[i-1] + fibs[i-2]) # Calculate the next Fibonacci number
 i += 1

 fib = fibs[-1]
 perfect_squares = [i**2 for i in range(1, int(math.sqrt(fib)) + 1)]
 max_square = max(filter(lambda x: x < fib, perfect_squares))
 return max_square
```

----------------

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.awt.Color;
public class ImmutableCircleTest {
    @Test
    public void testGetColor() {
        ImmutableCircle circle = new ImmutableCircle(Color.RED);
        assertEquals(Color.RED, circle.getColor());
    }
    @Test
    public void testChangeColor() {
        ImmutableCircle circle = new ImmutableCircle(Color.RED);
        assertThrows(UnsupportedOperationException.class, () -> {
            circle.changeColor(Color.BLUE);
        });
    }
    @Test
    public void testConstructor() {
        ImmutableCircle circle = new ImmutableCircle(Color.GREEN);
        assertNotNull(circle);
    }
    @Test
    public void testColorIsImmutable() {
        ImmutableCircle circle = new ImmutableCircle(Color.YELLOW);
        assertThrows(UnsupportedOperationException.class, () -> {
            circle.changeColor(Color.BLACK);
        });
        assertEquals(Color.YELLOW, circle.getColor());
    }
    @Test
    public void testUnsupportedOperationExceptionMessage() {
        ImmutableCircle circle = new ImmutableCircle(Color.BLUE);
        UnsupportedOperationException exception = assertThrows(UnsupportedOperationException.class, () -> {
            circle.changeColor(Color.WHITE);
        });
        assertEquals("圆形是不可变的，不能改变颜色", exception.getMessage());
    }
}


import org.junit.jupiter.api.Assertions;
public class SchoolManagement {
    static class Course {
        private String code;
        private String name;
        private int semester;
        private int credits;
        public Course(String code, String name, int semester, int credits) {
            this.code = code;
            this.name = name;
            this.semester = semester;
            this.credits = credits;
        }
        public String getCode() {
            return code;
        }
    }
    public static void testCourseGetCode() {
        Course course = new Course("ENG101", "English Basics", 1, 4);
        Assertions.assertEquals("ENG101", course.getCode());
    }
    public static void main(String[] args) {
        testCourseGetCode();
    }
}

Please write a Java program to manage school course information. Specific requirements are as follows:

- There needs to be a Course class that includes four attributes: course code (code), course name (name), semester (semester), and credits (credits).
- Provide a constructor for the Course class that can initialize these four attributes.
- Provide a method `getCode()` to retrieve the course code.

Ensure the code is self-contained and clear, including necessary package imports.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import org.junit.jupiter.api.Assertions;
public class SchoolManagement {
    static class Course {
        private String code;
        private String name;
        private int semester;
        private int credits;
        public Course(String code, String name, int semester, int credits) {
        }
        public String getCode() {
            return code;
        }
    }
}
```

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class SchoolManagementTest {
    @Test
    public void testCourseConstructorAndGetters() {
        SchoolManagement.Course course = new SchoolManagement.Course("ENG101", "English Basics", 1, 4);
        Assertions.assertEquals("ENG101", course.getCode());
        Assertions.assertNotNull(course);
        Assertions.assertEquals("ENG101", course.getCode());
    }
    @Test
    public void testCourseCode() {
        SchoolManagement.Course course = new SchoolManagement.Course("CS101", "Computer Science Basics", 1, 3);
        Assertions.assertEquals("CS101", course.getCode());
    }
    @Test
    public void testInvalidCourseCode() {
        SchoolManagement.Course course = new SchoolManagement.Course("MAT101", "Mathematics Basics", 1, 3);
        Assertions.assertNotEquals("PHY101", course.getCode());
    }
    @Test
    public void testCourseWithDifferentSemester() {
        SchoolManagement.Course course = new SchoolManagement.Course("HIS101", "History Basics", 2, 3);
        Assertions.assertEquals("HIS101", course.getCode());
    }
    @Test
    public void testCourseWithDifferentCredits() {
        SchoolManagement.Course course = new SchoolManagement.Course("BIO101", "Biology Basics", 1, 5);
        Assertions.assertEquals("BIO101", course.getCode());
    }
}


import java.util.HashMap;
import java.util.Map;
public class BookFinder {
    private static Map<String, String[]> booksDatabase = new HashMap<>();
    static {
        booksDatabase.put("001", new String[]{"Java基础", "张三"});
        booksDatabase.put("002", new String[]{"算法导论", "李四"});
        booksDatabase.put("003", new String[]{"操作系统", "王五"});
    }
    public static String getBookDetails(String bookId) {
        if (booksDatabase.containsKey(bookId)) {
            String[] details = booksDatabase.get(bookId);
            return "书名: " + details[0] + ", 作者: " + details[1];
        } else {
            return "错误：图书ID不存在。";
        }
    }
    public static void main(String[] args) {
        System.out.println(getBookDetails("001"));
        System.out.println(getBookDetails("004"));
    }
}

Please write a Java method that can query and return specific book information. Assume we have a book management system where each book has a unique ID, title, and author. We now need to fetch detailed information about a book based on its ID. Please implement a method named `getBookDetails` that receives the book ID as a parameter and returns a string containing the title and author. If the book ID does not exist, it should return a specified error message string.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class BookFinder {
    private static Map<String, String[]> booksDatabase = new HashMap<>();
    static {
        booksDatabase.put("001", new String[]{"Java基础", "张三"});
        booksDatabase.put("002", new String[]{"算法导论", "李四"});
        booksDatabase.put("003", new String[]{"操作系统", "王五"});
    }
    public static String getBookDetails(String bookId) {
    }
}
```

import org.junit.Test;
import org.junit.Assert;
public class BookFinderTest {
    @Test
    public void testValidBookId() {
        String bookId = "001";
        String expected = "书名: Java基础, 作者: 张三";
        String actual = BookFinder.getBookDetails(bookId);
        Assert.assertEquals(expected, actual);
    }
    @Test
    public void testValidBookId2() {
        String bookId = "002";
        String expected = "书名: 算法导论, 作者: 李四";
        String actual = BookFinder.getBookDetails(bookId);
        Assert.assertEquals(expected, actual);
    }
    @Test
    public void testInvalidBookId() {
        String bookId = "004";
        String expected = "错误：图书ID不存在。";
        String actual = BookFinder.getBookDetails(bookId);
        Assert.assertEquals(expected, actual);
    }
    @Test
    public void testValidBookId3() {
        String bookId = "003";
        String expected = "书名: 操作系统, 作者: 王五";
        String actual = BookFinder.getBookDetails(bookId);
        Assert.assertEquals(expected, actual);
    }
    @Test
    public void testEmptyBookId() {
        String bookId = "";
        String expected = "错误：图书ID不存在。";
        String actual = BookFinder.getBookDetails(bookId);
        Assert.assertEquals(expected, actual);
    }
}


import java.util.Set;
import java.util.HashSet;
class DefaultTask {
    public static final java.util.Map<String, Set<String>> DEFAULT_TOOLS = new java.util.HashMap<>();
    static {
        Set<String> toolsForTaskA = new HashSet<>();
        toolsForTaskA.add("Tool1");
        toolsForTaskA.add("Tool2");
        DEFAULT_TOOLS.put("TaskA", toolsForTaskA);
        Set<String> toolsForTaskB = new HashSet<>();
        toolsForTaskB.add("Tool3");
        DEFAULT_TOOLS.put("TaskB", toolsForTaskB);
    }
}
class CustomTask {
    public static final java.util.Map<String, Set<String>> CUSTOM_TOOLS = new java.util.HashMap<>();
    static {
        Set<String> toolsForTaskC = new HashSet<>();
        toolsForTaskC.add("Tool4");
        CUSTOM_TOOLS.put("TaskC", toolsForTaskC);
    }
}
public class TaskToolFinder {
    public static Set<String> getRequiredTools(final String taskName) {
        if (DefaultTask.DEFAULT_TOOLS.containsKey(taskName)) {
            Set<String> requiredTools = new HashSet<>(DefaultTask.DEFAULT_TOOLS.get(taskName));
            requiredTools.add(taskName);
            return requiredTools;
        } else if (CustomTask.CUSTOM_TOOLS.containsKey(taskName)) {
            Set<String> requiredTools = new HashSet<>(CustomTask.CUSTOM_TOOLS.get(taskName));
            requiredTools.add(taskName);
            return requiredTools;
        } else {
            throw new IllegalArgumentException(String.format("%s is not a supported task.", taskName));
        }
    }
    public static void main(String[] args) {
        System.out.println(getRequiredTools("TaskA"));
        System.out.println(getRequiredTools("TaskC"));
        try {
            System.out.println(getRequiredTools("TaskX"));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Please write a Java method to get the names of all tools required for a specified task. Let's assume we have two types of tasks: default tasks and custom tasks, each requiring a specific set of tools to complete. The tool requirements for default tasks are defined in the `DefaultTask` class's `DEFAULT_TOOLS` constant, while the tool requirements for custom tasks are defined in the `CustomTask` class's `CUSTOM_TOOLS` constant. The method should accept a task name as an input parameter and return a set containing the names of the task and all its dependent tools. If the given task name is neither a default task nor a custom task, an `IllegalArgumentException` should be thrown.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Set;
import java.util.HashSet;
class DefaultTask {
    public static final java.util.Map<String, Set<String>> DEFAULT_TOOLS = new java.util.HashMap<>();
    static {
    }
}
class CustomTask {
    public static final java.util.Map<String, Set<String>> CUSTOM_TOOLS = new java.util.HashMap<>();
    static {
    }
}
public class TaskToolFinder {
    public static Set<String> getRequiredTools(final String taskName) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
class TaskToolFinderTest {
    @Test
    public void testGetRequiredToolsForTaskA() {
        Set<String> expectedTools = new HashSet<>();
        expectedTools.add("Tool1");
        expectedTools.add("Tool2");
        expectedTools.add("TaskA");
        assertEquals(expectedTools, TaskToolFinder.getRequiredTools("TaskA"));
    }
    @Test
    public void testGetRequiredToolsForTaskC() {
        Set<String> expectedTools = new HashSet<>();
        expectedTools.add("Tool4");
        expectedTools.add("TaskC");
        assertEquals(expectedTools, TaskToolFinder.getRequiredTools("TaskC"));
    }
    @Test
    public void testGetRequiredToolsForUnsupportedTask() {
        assertThrows(IllegalArgumentException.class, () -> {
            TaskToolFinder.getRequiredTools("TaskX");
        });
    }
    @Test
    public void testGetRequiredToolsForTaskB() {
        Set<String> expectedTools = new HashSet<>();
        expectedTools.add("Tool3");
        expectedTools.add("TaskB");
        assertEquals(expectedTools, TaskToolFinder.getRequiredTools("TaskB"));
    }
    @Test
    public void testGetRequiredToolsForAnotherUnsupportedTask() {
        assertThrows(IllegalArgumentException.class, () -> {
            TaskToolFinder.getRequiredTools("TaskD");
        });
    }
}


import java.util.Scanner;
public class SimpleCalculator {
    public double add(double a, double b) {
        return a + b;
    }
    public double subtract(double a, double b) {
        return a - b;
    }
    public double multiply(double a, double b) {
        return a * b;
    }
    public double divide(double a, double b) throws ArithmeticException {
        if (b == 0) {
            throw new ArithmeticException("不能除以零");
        }
        return a / b;
    }
    public static void main(String[] args) {
        SimpleCalculator calculator = new SimpleCalculator();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入两个数字和一个操作符（+、-、*、/），例如：3 4 +");
        double num1 = scanner.nextDouble();
        double num2 = scanner.nextDouble();
        char operator = scanner.next().charAt(0);
        try {
            switch (operator) {
                case '+':
                    System.out.println("结果是：" + calculator.add(num1, num2));
                    break;
                case '-':
                    System.out.println("结果是：" + calculator.subtract(num1, num2));
                    break;
                case '*':
                    System.out.println("结果是：" + calculator.multiply(num1, num2));
                    break;
                case '/':
                    System.out.println("结果是：" + calculator.divide(num1, num2));
                    break;
                default:
                    System.out.println("未知的操作符：" + operator);
            }
        } catch (ArithmeticException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }
}

Please write a Java program to implement a simple calculator class `SimpleCalculator`. This class should be able to perform basic arithmetic operations: addition, subtraction, multiplication, and division. Ensure that your program handles the division by zero situation by throwing an `ArithmeticException` with the message "Cannot divide by zero".

Please follow these guidelines:

- The code must include all necessary import statements.
- The naming of classes and methods should be clear and concise.
- Use comments and documentation strings to enhance code readability.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Scanner;
public class SimpleCalculator {
    public double add(double a, double b) {
    }
    public double subtract(double a, double b) {
    }
    public double multiply(double a, double b) {
    }
    public double divide(double a, double b) throws ArithmeticException {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SimpleCalculatorTest {
    private SimpleCalculator calculator;
    @BeforeEach
    public void setup() {
        calculator = new SimpleCalculator();
    }
    @Test
    public void testAdd() {
        assertEquals(5.0, calculator.add(2.0, 3.0));
        assertEquals(-1.0, calculator.add(-2.0, 1.0));
        assertEquals(0.0, calculator.add(2.0, -2.0));
    }
    @Test
    public void testSubtract() {
        assertEquals(-1.0, calculator.subtract(2.0, 3.0));
        assertEquals(-3.0, calculator.subtract(-2.0, 1.0));
        assertEquals(4.0, calculator.subtract(2.0, -2.0));
    }
    @Test
    public void testMultiply() {
        assertEquals(6.0, calculator.multiply(2.0, 3.0));
        assertEquals(-2.0, calculator.multiply(-2.0, 1.0));
        assertEquals(-4.0, calculator.multiply(2.0, -2.0));
    }
    @Test
    public void testDivide() {
        assertEquals(2.0, calculator.divide(6.0, 3.0));
        assertEquals(-2.0, calculator.divide(-6.0, 3.0));
        assertEquals(-1.0, calculator.divide(2.0, -2.0));
    }
    @Test
    public void testDivideByZero() {
        Exception exception = assertThrows(ArithmeticException.class, () -> {
            calculator.divide(1.0, 0.0);
        });
        assertEquals("不能除以零", exception.getMessage());
    }
}


import java.lang.IllegalArgumentException;
public class DirectionConverter {
    public static String convertToChineseName(int directionCode) {
        switch (directionCode) {
            case 1:
                return "上";
            case 2:
                return "下";
            case 3:
                return "左";
            case 4:
                return "右";
            default:
                throw new IllegalArgumentException("无效的方向代码");
        }
    }
    public static void checkFunction() {
        assert "上".equals(convertToChineseName(1)) : "代码1应该返回上";
        assert "下".equals(convertToChineseName(2)) : "代码2应该返回下";
        assert "左".equals(convertToChineseName(3)) : "代码3应该返回左";
        assert "右".equals(convertToChineseName(4)) : "代码4应该返回右";
        try {
            convertToChineseName(0);
            assert false : "无效的方向代码应该抛出异常";
        } catch (IllegalArgumentException e) {
        }
    }
    public static void main(String[] args) {
        checkFunction();
        System.out.println("所有测试通过！");
    }
}

Please write a Java method `convertToChineseName` that receives an integer parameter `directionCode` and returns the corresponding Chinese direction name based on the parameter. Specific requirements are as follows:

- If `directionCode` is 1, return "上".
- If `directionCode` is 2, return "下".
- If `directionCode` is 3, return "左".
- If `directionCode` is 4, return "右".
- If `directionCode` is not 1, 2, 3, or 4, throw an `IllegalArgumentException` with the message "无效的方向代码".
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.IllegalArgumentException;
public class DirectionConverter {
    public static String convertToChineseName(int directionCode) {
    }
    public static void checkFunction() {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
public class DirectionConverterTest {
    @Test
    public void testConvertToChineseName_Up() {
        assertEquals("上", DirectionConverter.convertToChineseName(1));
    }
    @Test
    public void testConvertToChineseName_Down() {
        assertEquals("下", DirectionConverter.convertToChineseName(2));
    }
    @Test
    public void testConvertToChineseName_Left() {
        assertEquals("左", DirectionConverter.convertToChineseName(3));
    }
    @Test
    public void testConvertToChineseName_Right() {
        assertEquals("右", DirectionConverter.convertToChineseName(4));
    }
    @Test(expected = IllegalArgumentException.class)
    public void testConvertToChineseName_InvalidCode() {
        DirectionConverter.convertToChineseName(0);
    }
}


import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.util.List;
public class ScoreLoader {
    private JTable studentScoreTable;
    public ScoreLoader(JTable table) {
        this.studentScoreTable = table;
    }
    public void loadScoresToTable(List<Student> students) {
        DefaultTableModel model = (DefaultTableModel) studentScoreTable.getModel();
        model.setColumnIdentifiers(new Object[]{"姓名", "分数"});
        for (Student student : students) {
            model.addRow(new Object[]{student.getName(), student.getScore()});
        }
    }
    public static class Student {
        private String name;
        private int score;
        public Student(String name, int score) {
            this.name = name;
            this.score = score;
        }
        public String getName() {
            return name;
        }
        public int getScore() {
            return score;
        }
    }
    public static void main(String[] args) {
        JTable table = new JTable();
        ScoreLoader loader = new ScoreLoader(table);
        loader.loadScoresToTable(List.of(
                new Student("张三", 88),
                new Student("李四", 92),
                new Student("王五", 76)
        ));
        System.out.println(table.getModel().getValueAt(0, 0).equals("张三") &&
                           (int)table.getModel().getValueAt(0, 1) == 88);
        System.out.println(table.getModel().getValueAt(1, 0).equals("李四") &&
                           (int)table.getModel().getValueAt(1, 1) == 92);
        System.out.println(table.getModel().getValueAt(2, 0).equals("王五") &&
                           (int)table.getModel().getValueAt(2, 1) == 76);
    }
}

Please write a Java method that loads a set of students' grades into a graphical user interface (GUI) table. Assume you already have a table named `StudentScoreTable`, and you need to populate this table with students' names and their scores. The student information is provided via a list of student objects, with each student object containing the student's name and score. Ensure that your code can create an appropriate table model and correctly populate the table with student data.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.util.List;
public class ScoreLoader {
    private JTable studentScoreTable;
    public ScoreLoader(JTable table) {
    }
    public void loadScoresToTable(List<Student> students) {
    }
    public static class Student {
        private String name;
        private int score;
        public Student(String name, int score) {
        }
        public String getName() {
            return name;
        }
        public int getScore() {
            return score;
        }
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ScoreLoaderTest {
    private JTable table;
    private ScoreLoader loader;
    @BeforeEach
    public void setUp() {
        table = new JTable();
        loader = new ScoreLoader(table);
    }
    @Test
    public void testLoadScoresToTable() {
        List<ScoreLoader.Student> students = List.of(
                new ScoreLoader.Student("张三", 88),
                new ScoreLoader.Student("李四", 92),
                new ScoreLoader.Student("王五", 76)
        );
        loader.loadScoresToTable(students);
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        assertEquals("张三", model.getValueAt(0, 0));
        assertEquals(88, model.getValueAt(0, 1));
        assertEquals("李四", model.getValueAt(1, 0));
        assertEquals(92, model.getValueAt(1, 1));
        assertEquals("王五", model.getValueAt(2, 0));
        assertEquals(76, model.getValueAt(2, 1));
    }
    @Test
    public void testEmptyStudentList() {
        List<ScoreLoader.Student> students = new ArrayList<>();
        loader.loadScoresToTable(students);
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        assertEquals(0, model.getRowCount());
    }
    @Test
    public void testNullStudentList() {
        assertThrows(NullPointerException.class, () -> {
            loader.loadScoresToTable(null);
        });
    }
    @Test
    public void testSingleStudent() {
        List<ScoreLoader.Student> students = List.of(
                new ScoreLoader.Student("单一学生", 100)
        );
        loader.loadScoresToTable(students);
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        assertEquals("单一学生", model.getValueAt(0, 0));
        assertEquals(100, model.getValueAt(0, 1));
    }
    @Test
    public void testLoadMultipleStudent() {
        List<ScoreLoader.Student> students = List.of(
                new ScoreLoader.Student("学生A", 80),
                new ScoreLoader.Student("学生B", 90)
        );
        loader.loadScoresToTable(students);
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        assertEquals("学生A", model.getValueAt(0, 0));
        assertEquals(80, model.getValueAt(0, 1));
        assertEquals("学生B", model.getValueAt(1, 0));
        assertEquals(90, model.getValueAt(1, 1));
    }
}


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class BookManager {
    private final List<Book> books;
    public BookManager() {
        books = new ArrayList<>();
    }
    public void addBook(String name, String author) {
        books.add(new Book(name, author));
    }
    public Optional<Book> findBookByName(String name) {
        return books.stream()
                .filter(book -> book.getName().equals(name))
                .findFirst();
    }
    static class Book {
        private final String name;
        private final String author;
        public Book(String name, String author) {
            this.name = name;
            this.author = author;
        }
        public String getName() {
            return name;
        }
        public String getAuthor() {
            return author;
        }
        @Override
        public String toString() {
            return "Book{" +
                    "name='" + name + '\'' +
                    ", author='" + author + '\'' +
                    '}';
        }
    }
    public static void main(String[] args) {
        BookManager manager = new BookManager();
        manager.addBook("Java编程思想", "Bruce Eckel");
        manager.addBook("Effective Java", "Joshua Bloch");
        check(manager);
    }
    private static void check(BookManager manager) {
        System.out.println("查询 'Java编程思想': " + manager.findBookByName("Java编程思想").orElse(null));
        System.out.println("查询 'Effective Java': " + manager.findBookByName("Effective Java").orElse(null));
        System.out.println("查询 '不存在的书': " + manager.findBookByName("不存在的书").orElse(null));
    }
}

Please write a Java program to implement a simple book management system. The system should allow users to add book information and query book information based on the book's name. Each book's information includes the book's name and author.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class BookManager {
    private final List<Book> books;
    public BookManager() {
    }
    public void addBook(String name, String author) {
    }
    public Optional<Book> findBookByName(String name) {
    }
    static class Book {
        private final String name;
        private final String author;
        public Book(String name, String author) {
        }
        public String getName() {
        }
        public String getAuthor() {
        }
        @Override
        public String toString() {
        }
    }
}
```

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
public class BookManagerTest {
    private BookManager bookManager;
    @BeforeEach
    void setUp() {
        bookManager = new BookManager();
    }
    @Test
    void testAddBookAndFindBookByName() {
        bookManager.addBook("Java编程思想", "Bruce Eckel");
        Optional<BookManager.Book> result = bookManager.findBookByName("Java编程思想");
        assertTrue(result.isPresent());
        assertEquals("Java编程思想", result.get().getName());
        assertEquals("Bruce Eckel", result.get().getAuthor());
    }
    @Test
    void testFindBookByNameWhenBookDoesNotExist() {
        Optional<BookManager.Book> result = bookManager.findBookByName("不存在的书");
        assertFalse(result.isPresent());
    }
    @Test
    void testAddMultipleBooksAndFindEachByName() {
        bookManager.addBook("Java编程思想", "Bruce Eckel");
        bookManager.addBook("Effective Java", "Joshua Bloch");
        Optional<BookManager.Book> result1 = bookManager.findBookByName("Java编程思想");
        assertTrue(result1.isPresent());
        assertEquals("Java编程思想", result1.get().getName());
        assertEquals("Bruce Eckel", result1.get().getAuthor());
        Optional<BookManager.Book> result2 = bookManager.findBookByName("Effective Java");
        assertTrue(result2.isPresent());
        assertEquals("Effective Java", result2.get().getName());
        assertEquals("Joshua Bloch", result2.get().getAuthor());
    }
    @Test
    void testBookToString() {
        BookManager.Book book = new BookManager.Book("Java编程思想", "Bruce Eckel");
        String expectedString = "Book{name='Java编程思想', author='Bruce Eckel'}";
        assertEquals(expectedString, book.toString());
    }
    @Test
    void testGettersForBook() {
        BookManager.Book book = new BookManager.Book("Java编程思想", "Bruce Eckel");
        assertEquals("Java编程思想", book.getName());
        assertEquals("Bruce Eckel", book.getAuthor());
    }
}


import java.util.HashMap;
import java.util.Map;
public class BookManager {
    private Map<String, String> bookStatusMap;
    public BookManager() {
        bookStatusMap = new HashMap<>();
    }
    public void updateBookStatus(String bookId, String newStatus) {
        bookStatusMap.put(bookId, newStatus);
    }
    public String checkStatus(String bookId) {
        return bookStatusMap.getOrDefault(bookId, "UNKNOWN");
    }
    public static void main(String[] args) {
        BookManager manager = new BookManager();
        manager.updateBookStatus("123", "AVAILABLE");
        manager.updateBookStatus("456", "BORROWED");
        manager.updateBookStatus("789", "UNDER_REPAIR");
        System.out.println("书籍123的状态: " + manager.checkStatus("123"));
        System.out.println("书籍456的状态: " + manager.checkStatus("456"));
        System.out.println("书籍789的状态: " + manager.checkStatus("789"));
        System.out.println("书籍000的状态: " + manager.checkStatus("000"));
    }
}

Please design a simple Java program to manage the borrowing status of books in a library. Each book in the library can be in one of three statuses: AVAILABLE, BORROWED, or UNDER_REPAIR. You need to implement a class named `BookManager`, which contains a method called `updateBookStatus`. This method takes two parameters: `bookId` (the unique identifier of the book) and `newStatus` (the new status of the book), and updates the status of the book based on this information.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class BookManager {
    private Map<String, String> bookStatusMap;
    public BookManager() {
    }
    public void updateBookStatus(String bookId, String newStatus) {
    }
    public String checkStatus(String bookId) {
    }
}
```

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class BookManagerTest {
    private BookManager bookManager;
    @Before
    public void setUp() {
        bookManager = new BookManager();
    }
    @Test
    public void testUpdateBookStatus() {
        bookManager.updateBookStatus("123", "AVAILABLE");
        String status = bookManager.checkStatus("123");
        Assert.assertEquals("AVAILABLE", status);
    }
    @Test
    public void testCheckStatusWithUnknownBook() {
        String status = bookManager.checkStatus("000");
        Assert.assertEquals("UNKNOWN", status);
    }
    @Test
    public void testUpdateBookStatusMultipleUpdates() {
        bookManager.updateBookStatus("456", "BORROWED");
        bookManager.updateBookStatus("456", "AVAILABLE");
        String status = bookManager.checkStatus("456");
        Assert.assertEquals("AVAILABLE", status);
    }
    @Test
    public void testCheckStatusUnderRepair() {
        bookManager.updateBookStatus("789", "UNDER_REPAIR");
        String status = bookManager.checkStatus("789");
        Assert.assertEquals("UNDER_REPAIR", status);
    }
    @Test
    public void testUpdateDifferentBooks() {
        bookManager.updateBookStatus("123", "AVAILABLE");
        bookManager.updateBookStatus("456", "BORROWED");
        bookManager.updateBookStatus("789", "UNDER_REPAIR");
        Assert.assertEquals("AVAILABLE", bookManager.checkStatus("123"));
        Assert.assertEquals("BORROWED", bookManager.checkStatus("456"));
        Assert.assertEquals("UNDER_REPAIR", bookManager.checkStatus("789"));
    }
}


import java.text.DecimalFormat;
public class BankAccount {
    public double calculateInterest(double amount, int duration) {
        double annualInterestRate = 0.05;
        double interest = amount * annualInterestRate * duration;
        return interest;
    }
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        double interest = account.calculateInterest(10000, 2);
        DecimalFormat df = new DecimalFormat("#.00");
        System.out.println("计算得到的利息为: " + df.format(interest) + "元");
        check(interest);
    }
    public static void check(double calculatedInterest) {
        double expectedInterest = 1000.0;
        if (Math.abs(calculatedInterest - expectedInterest) < 0.01) {
            System.out.println("计算结果正确。");
        } else {
            System.out.println("计算结果不正确，预期的利息为: " + expectedInterest + "元，但计算得到: " + calculatedInterest + "元。");
        }
    }
}

Please write a Java program to calculate the interest for a bank account. The program should include a class named `BankAccount`, which contains a method named `calculateInterest`. This method accepts two parameters: `amount` (principal amount) and `duration` (deposit period in years), and returns the calculated interest value. Assume the annual interest rate is 5%.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.text.DecimalFormat;
public class BankAccount {
    public double calculateInterest(double amount, int duration) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BankAccountTest {
    @Test
    public void testCalculateInterest_10000_2() {
        BankAccount account = new BankAccount();
        double interest = account.calculateInterest(10000, 2);
        assertEquals(1000.0, interest, 0.01);
    }
    @Test
    public void testCalculateInterest_5000_1() {
        BankAccount account = new BankAccount();
        double interest = account.calculateInterest(5000, 1);
        assertEquals(250.0, interest, 0.01);
    }
    @Test
    public void testCalculateInterest_20000_3() {
        BankAccount account = new BankAccount();
        double interest = account.calculateInterest(20000, 3);
        assertEquals(3000.0, interest, 0.01);
    }
    @Test
    public void testCalculateInterest_0_Any() {
        BankAccount account = new BankAccount();
        double interest = account.calculateInterest(0, 5);
        assertEquals(0.0, interest, 0.01);
    }
    @Test
    public void testCalculateInterest_NegativeAmount() {
        BankAccount account = new BankAccount();
        double interest = account.calculateInterest(-10000, 2);
        assertEquals(-1000.0, interest, 0.01);
    }
}


import java.awt.Component;
import java.awt.Cursor;
public class CursorUpdater {
    private Component uiComponent;
    public CursorUpdater(Component uiComponent) {
        this.uiComponent = uiComponent;
    }
    public void updateCursorStyle(Cursor newCursor) {
        if (newCursor == null) {
            uiComponent.setCursor(Cursor.getDefaultCursor());
        } else {
            uiComponent.setCursor(newCursor);
        }
    }
    public static void main(String[] args) {
        Component dummyComponent = new Component() {};
        CursorUpdater cursorUpdater = new CursorUpdater(dummyComponent);
        cursorUpdater.updateCursorStyle(null);
        assert dummyComponent.getCursor().getType() == Cursor.DEFAULT_CURSOR : "光标应该设置为默认光标";
        Cursor customCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
        cursorUpdater.updateCursorStyle(customCursor);
        assert dummyComponent.getCursor().getType() == Cursor.HAND_CURSOR : "光标应该设置为手形光标";
        System.out.println("所有测试通过！");
    }
}

Please write a Java method to update the mouse cursor style for a user interface component. If the passed cursor object is `null`, the component's cursor should be set to the default cursor. Otherwise, the component's cursor should be set to the style of the passed cursor. Ensure that your implementation can handle type casting and does not raise exceptions when setting the cursor.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.awt.Component;
import java.awt.Cursor;
public class CursorUpdater {
    private Component uiComponent;
    public CursorUpdater(Component uiComponent) {
    }
    public void updateCursorStyle(Cursor newCursor) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.awt.Component;
import java.awt.Cursor;
public class CursorUpdaterTest {
    private Component dummyComponent;
    private CursorUpdater cursorUpdater;
    @BeforeEach
    public void setUp() {
        dummyComponent = new Component() {};
        cursorUpdater = new CursorUpdater(dummyComponent);
    }
    @Test
    public void testUpdateCursorStyleWithNull() {
        cursorUpdater.updateCursorStyle(null);
        assertEquals(Cursor.getDefaultCursor(), dummyComponent.getCursor(), "光标应该设置为默认光标");
    }
    @Test
    public void testUpdateCursorStyleWithHandCursor() {
        Cursor customCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
        cursorUpdater.updateCursorStyle(customCursor);
        assertEquals(customCursor, dummyComponent.getCursor(), "光标应该设置为手形光标");
    }
    @Test
    public void testUpdateCursorStyleWithWaitCursor() {
        Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        cursorUpdater.updateCursorStyle(waitCursor);
        assertEquals(waitCursor, dummyComponent.getCursor(), "光标应该设置为等待光标");
    }
    @Test
    public void testUpdateCursorStyleWithCrosshairCursor() {
        Cursor crosshairCursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
        cursorUpdater.updateCursorStyle(crosshairCursor);
        assertEquals(crosshairCursor, dummyComponent.getCursor(), "光标应该设置为十字光标");
    }
    @Test
    public void testUpdateCursorStyleWithMoveCursor() {
        Cursor moveCursor = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR);
        cursorUpdater.updateCursorStyle(moveCursor);
        assertEquals(moveCursor, dummyComponent.getCursor(), "光标应该设置为移动光标");
    }
}


import java.util.Map;
public class LibraryReportGenerator {
    public static String generateReport(Map<String, Integer> bookStats) {
        StringBuilder report = new StringBuilder();
        bookStats.forEach((type, quantity) -> report.append(type).append(": ").append(quantity).append("\n"));
        return report.toString();
    }
    public static void main(String[] args) {
        Map<String, Integer> bookStats = Map.of(
            "小说", 150,
            "科幻", 90,
            "历史", 120
        );
        String report = generateReport(bookStats);
        System.out.println(report);
        checkReport(report);
    }
    private static void checkReport(String report) {
        assert report.contains("小说: 150");
        assert report.contains("科幻: 90");
        assert report.contains("历史: 120");
        System.out.println("报告生成正确！");
    }
}

Please write a Java method to generate a simple report showing the number of books of different types in a virtual library. The report should be returned in text format, with each type of book on a new line in the format "Type: Quantity". The book types and their counts are passed through a `Map<String, Integer>` parameter, where the key is the book type and the value is the number of books of that type. Ensure that the method includes all necessary import statements.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Map;
public class LibraryReportGenerator {
    public static String generateReport(Map<String, Integer> bookStats) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Map;
public class LibraryReportGeneratorTest {
    @Test
    public void testGenerateReportWithValidData() {
        Map<String, Integer> bookStats = Map.of(
            "小说", 150,
            "科幻", 90,
            "历史", 120
        );
        String report = LibraryReportGenerator.generateReport(bookStats);
        assertTrue(report.contains("小说: 150"));
        assertTrue(report.contains("科幻: 90"));
        assertTrue(report.contains("历史: 120"));
    }
    @Test
    public void testGenerateReportWithEmptyData() {
        Map<String, Integer> bookStats = Map.of();
        String report = LibraryReportGenerator.generateReport(bookStats);
        assertEquals("", report);
    }
    @Test
    public void testGenerateReportWithSingleEntry() {
        Map<String, Integer> bookStats = Map.of("文学", 75);
        String report = LibraryReportGenerator.generateReport(bookStats);
        assertEquals("文学: 75\n", report);
    }
    @Test
    public void testGenerateReportWithMultipleEntries() {
        Map<String, Integer> bookStats = Map.of(
            "文学", 75,
            "艺术", 55,
            "科学", 100
        );
        String report = LibraryReportGenerator.generateReport(bookStats);
        assertTrue(report.contains("文学: 75"));
        assertTrue(report.contains("艺术: 55"));
        assertTrue(report.contains("科学: 100"));
    }
    @Test
    public void testGenerateReportWithZeroQuantity() {
        Map<String, Integer> bookStats = Map.of(
            "文学", 0,
            "艺术", 0
        );
        String report = LibraryReportGenerator.generateReport(bookStats);
        assertTrue(report.contains("文学: 0"));
        assertTrue(report.contains("艺术: 0"));
    }
}


import java.util.ArrayList;
public class ShoppingCart {
    private ArrayList<String> items;
    public void addItem(String itemName) {
        if (items == null) {
            items = new ArrayList<>();
        }
        items.add(itemName);
    }
    public void removeItem(String itemName) {
        if (items != null) {
            items.remove(itemName);
            if (items.isEmpty()) {
                items = null;
            }
        }
    }
    public boolean isEmpty() {
        return items == null;
    }
}
class ShoppingCartTest {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        cart.addItem("苹果");
        cart.addItem("香蕉");
        cart.removeItem("苹果");
        cart.removeItem("香蕉");
        if (cart.isEmpty()) {
            System.out.println("测试成功：购物车为空。");
        } else {
            System.out.println("测试失败：购物车不应该有商品。");
        }
    }
}

Please write a Java program to implement a simple shopping cart function. In this shopping cart, users can add product names to the cart list, and they can also remove specified product names from the list. If the cart becomes empty, it should be set to null, indicating that the cart is empty.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
public class ShoppingCart {
    private ArrayList<String> items;
    public void addItem(String itemName) {
    }
    public void removeItem(String itemName) {
    }
    public boolean isEmpty() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ShoppingCartTest {
    @Test
    void testAddItem() {
        ShoppingCart cart = new ShoppingCart();
        cart.addItem("苹果");
        assertFalse(cart.isEmpty());
    }
    @Test
    void testRemoveLastItem() {
        ShoppingCart cart = new ShoppingCart();
        cart.addItem("苹果");
        cart.removeItem("苹果");
        assertTrue(cart.isEmpty());
    }
    @Test
    void testRemoveItemFromMultiple() {
        ShoppingCart cart = new ShoppingCart();
        cart.addItem("苹果");
        cart.addItem("香蕉");
        cart.removeItem("苹果");
        assertFalse(cart.isEmpty());
    }
    @Test
    void testRemoveNonExistentItem() {
        ShoppingCart cart = new ShoppingCart();
        cart.addItem("苹果");
        cart.removeItem("香蕉");
        assertFalse(cart.isEmpty());
    }
    @Test
    void testIsEmptyWhenNew() {
        ShoppingCart cart = new ShoppingCart();
        assertTrue(cart.isEmpty());
    }
}


import java.util.Date;
class Order {
    private String orderId;
    private String status;
    private long cancellationTimestamp;
    public Order(String orderId, String status) {
        this.orderId = orderId;
        this.status = status;
        this.cancellationTimestamp = 0;
    }
    public String getOrderId() {
        return orderId;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public long getCancellationTimestamp() {
        return cancellationTimestamp;
    }
    public void setCancellationTimestamp(long cancellationTimestamp) {
        this.cancellationTimestamp = cancellationTimestamp;
    }
}
public class OrderCancellation {
    public Order cancelOrder(Order order) {
        if (!"CANCELLED".equals(order.getStatus())) {
            order.setStatus("CANCELLED");
            order.setCancellationTimestamp(System.currentTimeMillis());
        }
        return order;
    }
    public static void main(String[] args) {
        OrderCancellation orderCancellation = new OrderCancellation();
        Order order = new Order("12345", "PROCESSING");
        System.out.println("订单取消前的状态: " + order.getStatus());
        order = orderCancellation.cancelOrder(order);
        System.out.println("订单取消后的状态: " + order.getStatus());
        System.out.println("订单取消的时间戳: " + new Date(order.getCancellationTimestamp()));
    }
}

Please design a Java program to handle the cancellation of online shopping orders. On an e-commerce platform, when a user decides to cancel an order, the system needs to perform a series of operations to update the order status and record the cancellation timestamp. Implement a class named `OrderCancellation` that contains a method named `cancelOrder`. This method takes an order object `Order` as a parameter and returns the updated order object. If the order has already been canceled, it should not perform any operation and should directly return the original order object. After the order is canceled, the order status should be updated to "CANCELLED" and the cancellation timestamp should be recorded.

Please follow these guidelines:
- The method should handle the case where the order has already been canceled, i.e., if the order status is already "CANCELLED," it should directly return the order object without making any modifications.
- After the order is canceled, the order status should be updated to "CANCELLED" and the cancellation timestamp should be recorded.
- Use `System.currentTimeMillis()` to get the current timestamp.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Date;
class Order {
    private String orderId;
    private String status;
    private long cancellationTimestamp;
    public Order(String orderId, String status) {}
    public String getOrderId() {}
    public String getStatus() {}
    public void setStatus(String status) {}
    public long getCancellationTimestamp() {}
    public void setCancellationTimestamp(long cancellationTimestamp) {}
}
public class OrderCancellation {
    public Order cancelOrder(Order order) {}
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class OrderTest {
    @Test
    void testInitialStatusAndOrderId() {
        Order order = new Order("12345", "PROCESSING");
        assertEquals("PROCESSING", order.getStatus());
        assertEquals("12345", order.getOrderId());
    }
    @Test
    void testCancelOrderChangesStatusAndTimestamp() {
        Order order = new Order("12345", "PROCESSING");
        OrderCancellation orderCancellation = new OrderCancellation();
        orderCancellation.cancelOrder(order);
        assertEquals("CANCELLED", order.getStatus());
        assertNotEquals(0, order.getCancellationTimestamp());
        assertTrue(order.getCancellationTimestamp() > 0);
    }
    @Test
    void testCancelAlreadyCancelledOrder() {
        Order order = new Order("12345", "CANCELLED");
        OrderCancellation orderCancellation = new OrderCancellation();
        long originalTimestamp = order.getCancellationTimestamp();
        orderCancellation.cancelOrder(order);
        assertEquals("CANCELLED", order.getStatus());
        assertEquals(originalTimestamp, order.getCancellationTimestamp());
    }
    @Test
    void testSetAndGetOrderStatus() {
        Order order = new Order("12345", "PENDING");
        order.setStatus("SHIPPED");
        assertEquals("SHIPPED", order.getStatus());
    }
    @Test
    void testSetAndGetCancellationTimestamp() {
        Order order = new Order("12345", "PENDING");
        long currentTime = System.currentTimeMillis();
        order.setCancellationTimestamp(currentTime);
        assertEquals(currentTime, order.getCancellationTimestamp());
    }
}


import java.util.HashMap;
import java.util.Map;
public class WeatherSystem {
    private Map<String, String> weatherData;
    public WeatherSystem() {
        weatherData = new HashMap<>();
        weatherData.put("北京", "晴天");
        weatherData.put("上海", "多云");
        weatherData.put("广州", "雨天");
    }
    public String getWeather(String cityName) {
        if (weatherData.containsKey(cityName)) {
            return weatherData.get(cityName);
        } else {
            return "城市名称无效";
        }
    }
    public static void checkWeather() {
        WeatherSystem system = new WeatherSystem();
        System.out.println("北京的天气状况是：" + system.getWeather("北京"));
        System.out.println("上海的天气状况是：" + system.getWeather("上海"));
        System.out.println("广州的天气状况是：" + system.getWeather("广州"));
        System.out.println("深圳的天气状况是：" + system.getWeather("深圳"));
    }
    public static void main(String[] args) {
        checkWeather();
    }
}

Please design a simple Java program to simulate a basic weather system. In this system, we need to be able to return the current weather conditions for a given city name. To simplify the problem, we assume there are only three cities: Beijing, Shanghai, and Guangzhou, with their weather conditions being sunny, cloudy, and rainy, respectively. Please implement a class named `WeatherSystem`, which contains a method named `getWeather` that accepts a string parameter (city name) and returns the corresponding city's weather condition. If the input city is not in our list, please return a message informing the user that the city name is invalid.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class WeatherSystem {
    private Map<String, String> weatherData;
    public WeatherSystem() {
    }
    public String getWeather(String cityName) {
    }
    public static void checkWeather() {
    }
}
```

import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class WeatherSystemTest {
    private WeatherSystem weatherSystem;
    @Before
    public void setUp() {
        weatherSystem = new WeatherSystem();
    }
    @Test
    public void testGetWeather_Beijing() {
        String result = weatherSystem.getWeather("北京");
        assertEquals("晴天", result);
    }
    @Test
    public void testGetWeather_Shanghai() {
        String result = weatherSystem.getWeather("上海");
        assertEquals("多云", result);
    }
    @Test
    public void testGetWeather_Guangzhou() {
        String result = weatherSystem.getWeather("广州");
        assertEquals("雨天", result);
    }
    @Test
    public void testGetWeather_InvalidCity() {
        String result = weatherSystem.getWeather("深圳");
        assertEquals("城市名称无效", result);
    }
    @Test
    public void testGetWeather_NullCity() {
        String result = weatherSystem.getWeather(null);
        assertEquals("城市名称无效", result);
    }
}


import java.lang.System;
public class TaskManager {
    private double priority;
    public TaskManager() {
        this.priority = 5.0;
    }
    public void boostTaskPriority(double priorityBoost) {
        this.priority += priorityBoost;
        if (this.priority > 10) {
            this.priority = 10;
        }
    }
    public double getPriority() {
        return this.priority;
    }
    public void checkPriorityBoost(double priorityBoost) {
        System.out.println("提升前的优先级: " + this.getPriority());
        this.boostTaskPriority(priorityBoost);
        System.out.println("提升后的优先级: " + this.getPriority());
    }
    public static void main(String[] args) {
        TaskManager taskManager = new TaskManager();
        taskManager.checkPriorityBoost(3.5);
        taskManager.checkPriorityBoost(5);
    }
}

Please write a Java program to implement a `TaskManager` class that contains a method `boostTaskPriority` to increase the priority of a task. The method takes a `double` parameter `priorityBoost`, representing the value by which the priority should be increased. If the boosted priority exceeds the maximum value of 10, the priority should be set to 10. Additionally, the class should include a `getPriority` method to retrieve the current task priority.

Please complete the programming task according to the following requirements:

- Use appropriate access modifiers to ensure encapsulation.
- When initializing, the default task priority should be 5.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.System;
public class TaskManager {
    private double priority;
    public TaskManager() {
    }
    public void boostTaskPriority(double priorityBoost) {
    }
    public double getPriority() {
    }
    public void checkPriorityBoost(double priorityBoost) {
    }
}
```

import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class TaskManagerTest {
    private TaskManager taskManager;
    @Before
    public void setUp() {
        taskManager = new TaskManager();
    }
    @Test
    public void testInitialPriority() {
        assertEquals(5.0, taskManager.getPriority(), 0.001);
    }
    @Test
    public void testBoostTaskPriorityWithinLimit() {
        taskManager.boostTaskPriority(3.5);
        assertEquals(8.5, taskManager.getPriority(), 0.001);
    }
    @Test
    public void testBoostTaskPriorityBeyondLimit() {
        taskManager.boostTaskPriority(6.0);
        assertEquals(10.0, taskManager.getPriority(), 0.001);
    }
    @Test
    public void testBoostTaskPriorityToExactLimit() {
        taskManager.boostTaskPriority(5.0);
        assertEquals(10.0, taskManager.getPriority(), 0.001);
    }
    @Test
    public void testBoostTaskPriorityMultipleTimes() {
        taskManager.boostTaskPriority(3.0);
        taskManager.boostTaskPriority(2.0);
        assertEquals(10.0, taskManager.getPriority(), 0.001);
    }
}


import java.util.Objects;
public class EmailValidator {
    private Email email;
    public EmailValidator(Email email) {
        this.email = email;
    }
    public void validateSubject(String expectedSubject) {
        if (this.email == null) {
            throw new IllegalArgumentException("Email object is null.");
        }
        String actualSubject = this.email.getSubject();
        if (!Objects.equals(actualSubject, expectedSubject)) {
            throw new IllegalArgumentException(String.format(
                "Expected email subject to be \"%s\" but was \"%s\".",
                expectedSubject, actualSubject));
        }
    }
    public static class Email {
        private String subject;
        public Email(String subject) {
            this.subject = subject;
        }
        public String getSubject() {
            return subject;
        }
    }
    public static void main(String[] args) {
        Email email = new Email("Hello World");
        EmailValidator validator = new EmailValidator(email);
        try {
            validator.validateSubject("Hello World");
            System.out.println("验证成功，主题符合预期。");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
        try {
            validator.validateSubject("Goodbye World");
        } catch (IllegalArgumentException e) {
            System.out.println("验证失败：" + e.getMessage());
        }
    }
}

Please write a Java method to verify whether an email object contains a specific subject. If the subject of the email does not match the given subject, an exception should be thrown, and the exception message should clearly specify the expected subject and the actual subject. Ensure that your code is self-contained and all necessary packages are imported.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Objects;
public class EmailValidator {
    private Email email;
    public EmailValidator(Email email) {
    }
    public void validateSubject(String expectedSubject) {
    }
    public static class Email {
        private String subject;
        public Email(String subject) {
        }
        public String getSubject() {
        }
    }
}
```

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
public class EmailValidatorTest {
    @Test
    public void testValidateSubject_Success() {
        EmailValidator.Email email = new EmailValidator.Email("Hello World");
        EmailValidator validator = new EmailValidator(email);
        validator.validateSubject("Hello World");
    }
    @Test
    public void testValidateSubject_Failure() {
        EmailValidator.Email email = new EmailValidator.Email("Hello World");
        EmailValidator validator = new EmailValidator(email);
        Assertions.assertThrows(IllegalArgumentException.class, () -> {
            validator.validateSubject("Goodbye World");
        });
    }
    @Test
    public void testValidateSubject_NullEmail() {
        EmailValidator validator = new EmailValidator(null);
        Assertions.assertThrows(IllegalArgumentException.class, () -> {
            validator.validateSubject("Hello World");
        });
    }
    @Test
    public void testValidateSubject_EmptySubject() {
        EmailValidator.Email email = new EmailValidator.Email("");
        EmailValidator validator = new EmailValidator(email);
        Assertions.assertThrows(IllegalArgumentException.class, () -> {
            validator.validateSubject("Hello World");
        });
    }
    @Test
    public void testValidateSubject_NullSubject() {
        EmailValidator.Email email = new EmailValidator.Email(null);
        EmailValidator validator = new EmailValidator(email);
        Assertions.assertThrows(IllegalArgumentException.class, () -> {
            validator.validateSubject("Hello World");
        });
    }
}


import java.util.ArrayList;
import java.util.List;
public class SimpleLibrarySystem {
    private List<Book> books;
    public SimpleLibrarySystem() {
        this.books = new ArrayList<>();
    }
    public void addBook(String title, String author) {
        books.add(new Book(title, author));
    }
    public void removeBook(String title) {
        books.removeIf(book -> book.title.equals(title));
    }
    public Book findBook(String title) {
        return books.stream()
                .filter(book -> book.title.equals(title))
                .findFirst()
                .orElse(null);
    }
    static class Book {
        String title;
        String author;
        public Book(String title, String author) {
            this.title = title;
            this.author = author;
        }
        @Override
        public String toString() {
            return "Book{" +
                    "title='" + title + '\'' +
                    ", author='" + author + '\'' +
                    '}';
        }
    }
    public static void main(String[] args) {
        SimpleLibrarySystem library = new SimpleLibrarySystem();
        library.addBook("Java编程思想", "Bruce Eckel");
        library.addBook("Effective Java", "Joshua Bloch");
        System.out.println(library.findBook("Java编程思想"));
        library.removeBook("Effective Java");
        System.out.println(library.findBook("Effective Java"));
    }
}

Please design a Java program to manage a simple library system. In this system, we need to be able to add books, delete books, and search for books. Each book contains a title and an author's name. Implement the following features:

1. Add a Book: Record the book's title and author when adding a new book.
2. Delete a Book: A book can be deleted from the system by its title.
3. Search for a Book: A book can be searched by its title, and detailed information about the book (title and author) should be returned.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.List;
public class SimpleLibrarySystem {
    private List<Book> books;
    public SimpleLibrarySystem() {}

    public void addBook(String title, String author) {}

    public void removeBook(String title) {}

    public Book findBook(String title) { return null; }

    static class Book {
        String title;
        String author;
        public Book(String title, String author) {}

        @Override
        public String toString() { return null; }
    }
}
```

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SimpleLibrarySystemTest {
    private SimpleLibrarySystem library;
    @BeforeEach
    public void setUp() {
        library = new SimpleLibrarySystem();
    }
    @Test
    public void testAddBook() {
        library.addBook("Java编程思想", "Bruce Eckel");
        SimpleLibrarySystem.Book book = library.findBook("Java编程思想");
        assertNotNull(book);
        assertEquals("Java编程思想", book.title);
        assertEquals("Bruce Eckel", book.author);
    }
    @Test
    public void testRemoveBook() {
        library.addBook("Java编程思想", "Bruce Eckel");
        library.addBook("Effective Java", "Joshua Bloch");
        library.removeBook("Effective Java");
        SimpleLibrarySystem.Book book = library.findBook("Effective Java");
        assertNull(book);
    }
    @Test
    public void testFindBookExists() {
        library.addBook("Effective Java", "Joshua Bloch");
        SimpleLibrarySystem.Book book = library.findBook("Effective Java");
        assertNotNull(book);
        assertEquals("Effective Java", book.title);
        assertEquals("Joshua Bloch", book.author);
    }
    @Test
    public void testFindBookDoesNotExist() {
        SimpleLibrarySystem.Book book = library.findBook("不存在的书名");
        assertNull(book);
    }
    @Test
    public void testRemoveBookNonExistent() {
        library.addBook("Java编程思想", "Bruce Eckel");
        library.removeBook("不存在的书名");
        SimpleLibrarySystem.Book book = library.findBook("Java编程思想");
        assertNotNull(book);
        assertEquals("Java编程思想", book.title);
        assertEquals("Bruce Eckel", book.author);
    }
}


import java.util.function.Predicate;
import java.util.regex.Pattern;
class InvalidPhoneNumberException extends Exception {
    public InvalidPhoneNumberException(String message) {
        super(message);
    }
}
public class PhoneNumberValidator {
    private static final String PHONE_NUMBER_PATTERN = "^(13|14|15|17|18)\\d{9}$";
    public boolean validatePhoneNumber(String phoneNumber) throws InvalidPhoneNumberException {
        Predicate<String> validatePhoneNumber = n -> n.matches(PHONE_NUMBER_PATTERN);
        boolean result = validatePhoneNumber.test(phoneNumber);
        if (result) {
            return true;
        } else {
            throw new InvalidPhoneNumberException("无效的手机号码");
        }
    }
    public static void main(String[] args) {
        PhoneNumberValidator validator = new PhoneNumberValidator();
        try {
            System.out.println(validator.validatePhoneNumber("13812345678"));
            System.out.println(validator.validatePhoneNumber("11812345678"));
        } catch (InvalidPhoneNumberException e) {
            System.out.println(e.getMessage());
        }
    }
}

Please write a Java program to validate if the user's input phone number meets specific format requirements. The format requirements for the phone number are as follows: it must start with "13", "14", "15", "17", or "18", followed by 9 digits. If the phone number meets the format requirements, the function returns `true`; if it does not, a custom exception `InvalidPhoneNumberException` should be thrown with the message "Invalid phone number".
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.function.Predicate;
import java.util.regex.Pattern;
class InvalidPhoneNumberException extends Exception {
    public InvalidPhoneNumberException(String message) {
        super(message);
    }
}
public class PhoneNumberValidator {
    private static final String PHONE_NUMBER_PATTERN = "^(13|14|15|17|18)\\d{9}$";
    public boolean validatePhoneNumber(String phoneNumber) throws InvalidPhoneNumberException {
    }
}
```

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
public class PhoneNumberValidatorTest {
    @Test
    public void testValidPhoneNumber() throws InvalidPhoneNumberException {
        PhoneNumberValidator validator = new PhoneNumberValidator();
        boolean isValid = validator.validatePhoneNumber("13812345678");
        Assertions.assertTrue(isValid);
    }
    @Test
    public void testInvalidPhoneNumber() {
        PhoneNumberValidator validator = new PhoneNumberValidator();
        Assertions.assertThrows(InvalidPhoneNumberException.class, () -> {
            validator.validatePhoneNumber("11812345678");
        });
    }
    @Test
    public void testValidPhoneNumberWithDifferentPrefix() throws InvalidPhoneNumberException {
        PhoneNumberValidator validator = new PhoneNumberValidator();
        boolean isValid = validator.validatePhoneNumber("15112345678");
        Assertions.assertTrue(isValid);
    }
    @Test
    public void testShortInvalidPhoneNumber() {
        PhoneNumberValidator validator = new PhoneNumberValidator();
        Assertions.assertThrows(InvalidPhoneNumberException.class, () -> {
            validator.validatePhoneNumber("138123");
        });
    }
    @Test
    public void testEmptyPhoneNumber() {
        PhoneNumberValidator validator = new PhoneNumberValidator();
        Assertions.assertThrows(InvalidPhoneNumberException.class, () -> {
            validator.validatePhoneNumber("");
        });
    }
}


import java.util.HashMap;
import java.util.Scanner;
public class BookSearchSystem {
    private static Scanner scanner = new Scanner(System.in);
    private static HashMap<Integer, String[]> books = new HashMap<>();
    public static void initializeBooks() {
        books.put(1, new String[]{"Java基础", "张三"});
        books.put(2, new String[]{"Python入门", "李四"});
        books.put(3, new String[]{"数据结构", "王五"});
    }
    public static void searchBook() {
        System.out.println("请输入图书编号：");
        int bookId = scanner.nextInt();
        if (books.containsKey(bookId)) {
            String[] bookInfo = books.get(bookId);
            System.out.println("图书名称：" + bookInfo[0] + ", 作者：" + bookInfo[1]);
        } else {
            System.out.println("错误：图书编号不存在。");
        }
    }
    public static void main(String[] args) {
        initializeBooks();
        searchBook();
    }
}

Please design a feature for a book management system that allows users to query book information. Users can search for book details, including the book's title and author, by entering the book's ID. If the entered ID does not exist, an appropriate error message should be displayed.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Scanner;
public class BookSearchSystem {
    private static Scanner scanner = new Scanner(System.in);
    private static HashMap<Integer, String[]> books = new HashMap<>();
    public static void initializeBooks() {
    }
    public static void searchBook() {
    }
}
```

import java.util.HashMap;
import java.util.Scanner;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BookSearchSystemTest {
    private static HashMap<Integer, String[]> books;
    @BeforeAll
    public static void initializeBooks() {
        books = new HashMap<>();
        books.put(1, new String[]{"Java基础", "张三"});
        books.put(2, new String[]{"Python入门", "李四"});
        books.put(3, new String[]{"数据结构", "王五"});
    }
    @Test
    public void testInitializeBooks() {
        assertEquals(3, books.size());
        assertArrayEquals(new String[]{"Java基础", "张三"}, books.get(1));
        assertArrayEquals(new String[]{"Python入门", "李四"}, books.get(2));
        assertArrayEquals(new String[]{"数据结构", "王五"}, books.get(3));
    }
    @Test
    public void testValidBookId() {
        int bookId = 1;
        assertTrue(books.containsKey(bookId));
        String[] bookInfo = books.get(bookId);
        assertAll("bookInfo",
            () -> assertEquals("Java基础", bookInfo[0]),
            () -> assertEquals("张三", bookInfo[1]));
    }
    @Test
    public void testInvalidBookId() {
        int bookId = 4;
        assertFalse(books.containsKey(bookId));
    }
    @Test
    public void testAnotherValidBookId() {
        int bookId = 3;
        assertTrue(books.containsKey(bookId));
        String[] bookInfo = books.get(bookId);
        assertAll("bookInfo",
            () -> assertEquals("数据结构", bookInfo[0]),
            () -> assertEquals("王五", bookInfo[1]));
    }
    @Test
    public void testAnotherInvalidBookId() {
        int bookId = 10;
        assertFalse(books.containsKey(bookId));
    }
}


import java.math.BigDecimal;
public class Departamento {
    private BigDecimal orcamentoFolha;
    public Departamento(BigDecimal orcamentoFolha) {
        this.orcamentoFolha = orcamentoFolha;
    }
    public BigDecimal getOrcamentoFolha() {
        return orcamentoFolha;
    }
    public void ajustaOrcamento(BigDecimal valor) {
        orcamentoFolha = orcamentoFolha.add(valor);
    }
}
public class Empregado {
    private Departamento departamento;
    private BigDecimal salario;
    public Empregado(Departamento departamento, BigDecimal salario) {
        this.departamento = departamento;
        this.salario = salario;
    }
    public Departamento getDepartamento() {
        return departamento;
    }
    public BigDecimal getSalario() {
        return salario;
    }
}
public class TransferenciaService {
    public boolean tentarTransferencia(Empregado empregadoNovo, Empregado empregadoAtual) {
        Departamento departamentoNovo = empregadoNovo.getDepartamento();
        if (empregadoNovo.getSalario().compareTo(departamentoNovo.getOrcamentoFolha()) <= 0) {
            Departamento departamentoAtual = empregadoAtual.getDepartamento();
            departamentoAtual.ajustaOrcamento(empregadoAtual.getSalario());
            departamentoNovo.ajustaOrcamento(empregadoNovo.getSalario().negate());
            return true;
        } else {
            return false;
        }
    }
}
public class Main {
    public static void main(String[] args) {
        Departamento departamentoAtual = new Departamento(new BigDecimal("10000"));
        Departamento departamentoNovo = new Departamento(new BigDecimal("20000"));
        Empregado empregadoAtual = new Empregado(departamentoAtual, new BigDecimal("3000"));
        Empregado empregadoNovo = new Empregado(departamentoNovo, new BigDecimal("4000"));
        TransferenciaService service = new TransferenciaService();
        boolean resultado = service.tentarTransferencia(empregadoNovo, empregadoAtual);
        System.out.println("Transferência foi " + (resultado ? "成功" : "失败"));
    }
}

Please write a Java method for handling the transfer of an employee from one department to another, and decide whether the transfer can take place based on the employee's new salary and the new department's budget. If the new department's budget is sufficient to cover the employee's salary, the transfer can proceed, and the budgets of the two departments need to be updated accordingly. If the budget is insufficient, the transfer will not happen.

Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.math.BigDecimal;
public class Departamento {
    private BigDecimal orcamentoFolha;
    public Departamento(BigDecimal orcamentoFolha) {
    }
    public BigDecimal getOrcamentoFolha() {
    }
    public void ajustaOrcamento(BigDecimal valor) {
    }
}
public class Empregado {
    private Departamento departamento;
    private BigDecimal salario;
    public Empregado(Departamento departamento, BigDecimal salario) {
    }
    public Departamento getDepartamento() {
    }
    public BigDecimal getSalario() {
    }
}
public class TransferenciaService {
    public boolean tentarTransferencia(Empregado empregadoNovo, Empregado empregadoAtual) {
    }
}
```

import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class DepartamentoTest {
    @Test
    void getOrcamentoFolhaTest() {
        Departamento departamento = new Departamento(new BigDecimal("10000"));
        assertEquals(new BigDecimal("10000"), departamento.getOrcamentoFolha());
    }
    @Test
    void ajustaOrcamentoPositivoTest() {
        Departamento departamento = new Departamento(new BigDecimal("10000"));
        departamento.ajustaOrcamento(new BigDecimal("5000"));
        assertEquals(new BigDecimal("15000"), departamento.getOrcamentoFolha());
    }
    @Test
    void ajustaOrcamentoNegativoTest() {
        Departamento departamento = new Departamento(new BigDecimal("10000"));
        departamento.ajustaOrcamento(new BigDecimal("-3000"));
        assertEquals(new BigDecimal("7000"), departamento.getOrcamentoFolha());
    }
}
class EmpregadoTest {
    @Test
    void getDepartamentoTest() {
        Departamento departamento = new Departamento(new BigDecimal("10000"));
        Empregado empregado = new Empregado(departamento, new BigDecimal("3000"));
        assertEquals(departamento, empregado.getDepartamento());
    }
    @Test
    void getSalarioTest() {
        Departamento departamento = new Departamento(new BigDecimal("10000"));
        Empregado empregado = new Empregado(departamento, new BigDecimal("3000"));
        assertEquals(new BigDecimal("3000"), empregado.getSalario());
    }
}
class TransferenciaServiceTest {
    @Test
    void tentarTransferenciaBemSucedidaTest() {
        Departamento departamentoAtual = new Departamento(new BigDecimal("10000"));
        Departamento departamentoNovo = new Departamento(new BigDecimal("20000"));
        Empregado empregadoAtual = new Empregado(departamentoAtual, new BigDecimal("3000"));
        Empregado empregadoNovo = new Empregado(departamentoNovo, new BigDecimal("4000"));
        TransferenciaService service = new TransferenciaService();
        assertTrue(service.tentarTransferencia(empregadoNovo, empregadoAtual));
    }
    @Test
    void tentarTransferenciaFalhaTest() {
        Departamento departamentoAtual = new Departamento(new BigDecimal("10000"));
        Departamento departamentoNovo = new Departamento(new BigDecimal("2000"));
        Empregado empregadoAtual = new Empregado(departamentoAtual, new BigDecimal("3000"));
        Empregado empregadoNovo = new Empregado(departamentoNovo, new BigDecimal("4000"));
        TransferenciaService service = new TransferenciaService();
        assertFalse(service.tentarTransferencia(empregadoNovo, empregadoAtual));
    }
    @Test
    void ajustarOrcamentosAposTransferenciaTest() {
        Departamento departamentoAtual = new Departamento(new BigDecimal("10000"));
        Departamento departamentoNovo = new Departamento(new BigDecimal("20000"));
        Empregado empregadoAtual = new Empregado(departamentoAtual, new BigDecimal("3000"));
        Empregado empregadoNovo = new Empregado(departamentoNovo, new BigDecimal("4000"));
        TransferenciaService service = new TransferenciaService();
        service.tentarTransferencia(empregadoNovo, empregadoAtual);
        assertEquals(new BigDecimal("13000"), departamentoAtual.getOrcamentoFolha());
        assertEquals(new BigDecimal("16000"), departamentoNovo.getOrcamentoFolha());
    }
}


import java.util.Objects;
class Student {
    private int id;
    private String name;
    public Student() {}
    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;
    }
}
class StudentView {
    private String name;
    private String email;
    public StudentView() {}
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}
public class StudentConverter {
    public static Student convertViewToModel(StudentView sv) {
        Student student = new Student();
        student.setName(sv.getName());
        return student;
    }
    public static void checkConversion() {
        StudentView sv = new StudentView();
        sv.setName("张三");
        sv.setEmail("zhangsan@example.com");
        Student student = convertViewToModel(sv);
        if (Objects.equals(student.getName(), "张三")) {
            System.out.println("转换正确！");
        } else {
            System.out.println("转换错误！");
        }
    }
    public static void main(String[] args) {
        checkConversion();
    }
}

Please write a Java function that converts a student’s view object to a model object. Suppose we have a student tracking system where the `Student` class represents the model layer and the `StudentView` class represents the view layer. The `Student` class contains the student’s ID and name, while the `StudentView` class contains the student's view information such as name and email. You need to complete a function called `convertViewToModel` that takes a `StudentView` object as a parameter and returns a `Student` object. Note that you need to fetch the student’s name from the `StudentView` object and set it to the corresponding attribute of the `Student` object. Also, ensure all necessary packages are imported.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Objects;
class Student {
    private int id;
    private String name;
    public Student() {}
    public int getId() {
    }
    public void setId(int id) {
    }
    public String getName() {
    }
    public void setName(String name) {
    }
}
class StudentView {
    private String name;
    private String email;
    public StudentView() {}
    public String getName() {
    }
    public void setName(String name) {
    }
    public String getEmail() {
    }
    public void setEmail(String email) {
    }
}
public class StudentConverter {
    public static Student convertViewToModel(StudentView sv) {
    }
    public static void checkConversion() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StudentTest {
    @Test
    void getId() {
        Student student = new Student();
        student.setId(1);
        assertEquals(1, student.getId());
    }
    @Test
    void getName() {
        Student student = new Student();
        student.setName("张三");
        assertEquals("张三", student.getName());
    }
    @Test
    void setName() {
        Student student = new Student();
        student.setName("李四");
        assertEquals("李四", student.getName());
    }
}
class StudentViewTest {
    @Test
    void getName() {
        StudentView studentView = new StudentView();
        studentView.setName("张三");
        assertEquals("张三", studentView.getName());
    }
    @Test
    void getEmail() {
        StudentView studentView = new StudentView();
        studentView.setEmail("zhangsan@example.com");
        assertEquals("zhangsan@example.com", studentView.getEmail());
    }
}
class StudentConverterTest {
    @Test
    void convertViewToModel() {
        StudentView studentView = new StudentView();
        studentView.setName("张三");
        Student student = StudentConverter.convertViewToModel(studentView);
        assertEquals("张三", student.getName());
    }
    @Test
    void convertViewToModelWithNullName() {
        StudentView studentView = new StudentView();
        studentView.setName(null);
        Student student = StudentConverter.convertViewToModel(studentView);
        assertNull(student.getName());
    }
    @Test
    void checkConversion() {
        StudentView studentView = new StudentView();
        studentView.setName("张三");
        studentView.setEmail("zhangsan@example.com");
        Student student = StudentConverter.convertViewToModel(studentView);
        assertEquals("张三", student.getName());
    }
}


import javax.swing.JComponent;
import java.awt.Rectangle;
public static Rectangle getComponentBounds(JComponent component) {
    Rectangle bounds = component.getBounds();
    return bounds;
}
public static void checkFunction() {
    JComponent fakeComponent = new JComponent() {
        @Override
        public Rectangle getBounds() {
            return new Rectangle(10, 10, 200, 100);
        }
    };
    Rectangle result = getComponentBounds(fakeComponent);
    assert result.x == 10 : "X坐标不正确";
    assert result.y == 10 : "Y坐标不正确";
    assert result.width == 200 : "宽度不正确";
    assert result.height == 100 : "高度不正确";
}
public static void main(String[] args) {
    checkFunction();
}

Please write a Java method that takes a Swing component as a parameter and returns the position and size of the component within its parent container. The method should return a `Rectangle` object that contains the component's x-coordinate, y-coordinate, width, and height. Ensure that your method can handle any type of Swing component.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import javax.swing.JComponent;
import java.awt.Rectangle;
public static Rectangle getComponentBounds(JComponent component) {
}
public static void checkFunction() {
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import javax.swing.JComponent;
import java.awt.Rectangle;
public class ComponentBoundsTest {
    private Rectangle getComponentBounds(JComponent component) {
        Rectangle bounds = component.getBounds();
        return bounds;
    }
    @Test
    void testGetComponentBounds() {
        JComponent fakeComponent = new JComponent() {
            @Override
            public Rectangle getBounds() {
                return new Rectangle(10, 10, 200, 100);
            }
        };
        Rectangle result = getComponentBounds(fakeComponent);
        assertEquals(10, result.x);
        assertEquals(10, result.y);
        assertEquals(200, result.width);
        assertEquals(100, result.height);
    }
    @Test
    void testGetComponentBoundsWithDifferentValues() {
        JComponent fakeComponent = new JComponent() {
            @Override
            public Rectangle getBounds() {
                return new Rectangle(5, 5, 150, 75);
            }
        };
        Rectangle result = getComponentBounds(fakeComponent);
        assertEquals(5, result.x);
        assertEquals(5, result.y);
        assertEquals(150, result.width);
        assertEquals(75, result.height);
    }
    @Test
    void testGetComponentBoundsWithZeroValues() {
        JComponent fakeComponent = new JComponent() {
            @Override
            public Rectangle getBounds() {
                return new Rectangle(0, 0, 0, 0);
            }
        };
        Rectangle result = getComponentBounds(fakeComponent);
        assertEquals(0, result.x);
        assertEquals(0, result.y);
        assertEquals(0, result.width);
        assertEquals(0, result.height);
    }
    @Test
    void testGetComponentBoundsWithNegativeValues() {
        JComponent fakeComponent = new JComponent() {
            @Override
            public Rectangle getBounds() {
                return new Rectangle(-10, -10, -200, -100);
            }
        };
        Rectangle result = getComponentBounds(fakeComponent);
        assertEquals(-10, result.x);
        assertEquals(-10, result.y);
        assertEquals(-200, result.width);
        assertEquals(-100, result.height);
    }
    @Test
    void testGetComponentBoundsWithMixedValues() {
        JComponent fakeComponent = new JComponent() {
            @Override
            public Rectangle getBounds() {
                return new Rectangle(-5, 5, 50, -25);
            }
        };
        Rectangle result = getComponentBounds(fakeComponent);
        assertEquals(-5, result.x);
        assertEquals(5, result.y);
        assertEquals(50, result.width);
        assertEquals(-25, result.height);
    }
}


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
class Book {
    private Long id;
    private String title;
    public Book(Long id, String title) {
        this.id = id;
        this.title = title;
    }
    public Long getId() {
        return id;
    }
    public String getTitle() {
        return title;
    }
}
class Library {
    private List<Book> books;
    public Library() {
        this.books = new ArrayList<>();
    }
    public List<Book> getBooks() {
        return books;
    }
    public void addBookToCollection(Long bookId, String bookTitle) {
        Optional<Book> existingBook = books.stream()
                                            .filter(book -> book.getId().equals(bookId))
                                            .findFirst();
        if (!existingBook.isPresent()) {
            books.add(new Book(bookId, bookTitle));
        }
    }
}
public class LibraryManagement {
    public static void main(String[] args) {
        Library library = new Library();
        library.addBookToCollection(1L, "Java编程思想");
        library.addBookToCollection(2L, "Effective Java");
        library.addBookToCollection(1L, "Java编程思想");
        checkBooks(library.getBooks());
    }
    private static void checkBooks(List<Book> books) {
        if (books.size() == 2) {
            System.out.println("书籍添加正确！");
        } else {
            System.out.println("书籍添加出现错误。");
        }
    }
}

Please write a Java method to add a book to the library's collection. Suppose we have two entities: `Library` and `Book`. Each `Library` object has a list of books representing the books collected by the library. Books are added to the library by their unique IDs. If the library already has the book, it will not be added again. Ensure that your implementation can handle the `Optional` type to avoid `NullPointerException`.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
class Book {
    private Long id;
    private String title;
    public Book(Long id, String title) {
    }
    public Long getId() {
    }
    public String getTitle() {
    }
}
class Library {
    private List<Book> books;
    public Library() {
    }
    public List<Book> getBooks() {
    }
    public void addBookToCollection(Long bookId, String bookTitle) {
    }
}
public class LibraryManagement {
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
class LibraryTest {
    @Test
    void testAddNewBook() {
        Library library = new Library();
        library.addBookToCollection(1L, "Java编程思想");
        List<Book> books = library.getBooks();
        assertEquals(1, books.size());
        assertEquals("Java编程思想", books.get(0).getTitle());
    }
    @Test
    void testAddDuplicateBook() {
        Library library = new Library();
        library.addBookToCollection(1L, "Java编程思想");
        library.addBookToCollection(1L, "Java编程思想");
        List<Book> books = library.getBooks();
        assertEquals(1, books.size());
    }
    @Test
    void testAddMultipleBooks() {
        Library library = new Library();
        library.addBookToCollection(1L, "Java编程思想");
        library.addBookToCollection(2L, "Effective Java");
        List<Book> books = library.getBooks();
        assertEquals(2, books.size());
        assertTrue(books.stream().anyMatch(book -> book.getId().equals(1L)));
        assertTrue(books.stream().anyMatch(book -> book.getId().equals(2L)));
    }
    @Test
    void testAddDifferentBooksSameTitle() {
        Library library = new Library();
        library.addBookToCollection(1L, "Java编程思想");
        library.addBookToCollection(2L, "Java编程思想");
        List<Book> books = library.getBooks();
        assertEquals(2, books.size());
        assertTrue(books.stream().anyMatch(book -> book.getId().equals(1L)));
        assertTrue(books.stream().anyMatch(book -> book.getId().equals(2L)));
    }
    @Test
    void testLibraryInitialization() {
        Library library = new Library();
        List<Book> books = library.getBooks();
        assertTrue(books.isEmpty());
    }
}