import java.util.HashMap;
import java.util.Map;
public class RobotArmController {
    private double armPower = 0;
    private Map<String, Boolean> controller1 = new HashMap<>();
    private Map<String, Boolean> controller2 = new HashMap<>();
    public RobotArmController() {
        controller1.put("up", false);
        controller1.put("down", false);
        controller2.put("up", false);
        controller2.put("down", false);
    }
    public void updateArmPower() {
        if (controller1.get("up") || controller2.get("up")) {
            armPower = 1;
        } else if (controller1.get("down") || controller2.get("down")) {
            armPower = -1;
        } else {
            armPower = 0;
        }
    }
    public void setControllerInput(int controllerNum, String button, boolean pressed) {
        if (controllerNum == 1) {
            controller1.put(button, pressed);
        } else if (controllerNum == 2) {
            controller2.put(button, pressed);
        }
    }
    public double getArmPower() {
        return armPower;
    }
    public static void main(String[] args) {
        RobotArmController controller = new RobotArmController();
        controller.setControllerInput(1, "up", true);
        controller.updateArmPower();
        System.out.println("手臂动力（向前移动）: " + controller.getArmPower());
        controller.setControllerInput(1, "up", false);
        controller.setControllerInput(2, "down", true);
        controller.updateArmPower();
        System.out.println("手臂动力（向后移动）: " + controller.getArmPower());
        controller.setControllerInput(2, "down", false);
        controller.updateArmPower();
        System.out.println("手臂动力（停止）: " + controller.getArmPower());
    }
}

Please write a program to control the movement of a simple robotic arm. The robotic arm can move forward, move backward, or stop. We will use two different controllers (Controller1 and Controller2) to control the movement of the robotic arm. If the upward button of either controller is pressed, the robotic arm should move forward; if the downward button of either controller is pressed, the robotic arm should move backward; if no buttons are pressed, the robotic arm should stop.
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 RobotArmController {
    private double armPower = 0;
    private Map<String, Boolean> controller1 = new HashMap<>();
    private Map<String, Boolean> controller2 = new HashMap<>();
    public RobotArmController() {
    }
    public void updateArmPower() {
    }
    public void setControllerInput(int controllerNum, String button, boolean pressed) {
    }
    public double getArmPower() {
    }
}
```

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RobotArmControllerTest {
    private RobotArmController controller;
    @BeforeEach
    public void setup() {
        controller = new RobotArmController();
    }
    @Test
    public void testUpdateArmPowerUp() {
        controller.setControllerInput(1, "up", true);
        controller.updateArmPower();
        assertEquals(1.0, controller.getArmPower(), 0.001);
    }
    @Test
    public void testUpdateArmPowerDown() {
        controller.setControllerInput(2, "down", true);
        controller.updateArmPower();
        assertEquals(-1.0, controller.getArmPower(), 0.001);
    }
    @Test
    public void testUpdateArmPowerStopAfterUp() {
        controller.setControllerInput(1, "up", true);
        controller.updateArmPower();
        controller.setControllerInput(1, "up", false);
        controller.updateArmPower();
        assertEquals(0.0, controller.getArmPower(), 0.001);
    }
    @Test
    public void testUpdateArmPowerStopAfterDown() {
        controller.setControllerInput(2, "down", true);
        controller.updateArmPower();
        controller.setControllerInput(2, "down", false);
        controller.updateArmPower();
        assertEquals(0.0, controller.getArmPower(), 0.001);
    }
    @Test
    public void testNoControllerInput() {
        controller.updateArmPower();
        assertEquals(0.0, controller.getArmPower(), 0.001);
    }
}


import java.util.Objects;
class Book {
    private String title;
    private String author;
    private int pages;
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
    public String getTitle() {
        return title;
    }
    public String getAuthor() {
        return author;
    }
    public int getPages() {
        return pages;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public void setPages(int pages) {
        this.pages = pages;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Book)) return false;
        Book book = (Book) o;
        return pages == book.pages &&
                Objects.equals(title, book.title) &&
                Objects.equals(author, book.author);
    }
    @Override
    public int hashCode() {
        return Objects.hash(title, author, pages);
    }
}
public class BookCloner {
    public static Book cloneBook(final Book book) {
        return new Book(book.getTitle(), book.getAuthor(), book.getPages());
    }
    public static void check() {
        Book originalBook = new Book("Java Programming", "Y. Daniel Liang", 1345);
        Book clonedBook = cloneBook(originalBook);
        if (originalBook.equals(clonedBook) && originalBook != clonedBook) {
            System.out.println("方法正确实现了功能。");
        } else {
            System.out.println("方法实现有误。");
        }
    }
    public static void main(String[] args) {
        check();
    }
}

Please write a Java method that accepts a `Book` object as a parameter and returns a new `Book` object, with the new object's contents being exactly the same as the passed-in `Book` object. Ensure that all properties are properly copied when creating the new object.

Requirements:
- Ensure your code is self-contained and includes all necessary import statements.
- Briefly describe the problem in the method's documentation string.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Objects;
class Book {
    private String title;
    private String author;
    private int pages;
    public Book(String title, String author, int pages) {
    }
    public String getTitle() {
    }
    public String getAuthor() {
    }
    public int getPages() {
    }
    public void setTitle(String title) {
    }
    public void setAuthor(String author) {
    }
    public void setPages(int pages) {
    }
    @Override
    public boolean equals(Object o) {
    }
    @Override
    public int hashCode() {
    }
}
public class BookCloner {
    public static Book cloneBook(final Book book) {
    }
    public static void check() {
    }
}
```

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.*;
class BookTest {
    @Test
    void testGetTitle() {
        Book book = new Book("Effective Java", "Joshua Bloch", 416);
        assertEquals("Effective Java", book.getTitle());
    }
    @Test
    void testSetTitle() {
        Book book = new Book("Effective Java", "Joshua Bloch", 416);
        book.setTitle("Java Concurrency in Practice");
        assertEquals("Java Concurrency in Practice", book.getTitle());
    }
    @Test
    void testEquals() {
        Book book1 = new Book("Effective Java", "Joshua Bloch", 416);
        Book book2 = new Book("Effective Java", "Joshua Bloch", 416);
        assertTrue(book1.equals(book2));
    }
    @Test
    void testHashCode() {
        Book book1 = new Book("Effective Java", "Joshua Bloch", 416);
        Book book2 = new Book("Effective Java", "Joshua Bloch", 416);
        assertEquals(book1.hashCode(), book2.hashCode());
    }
    @Test
    void testCloneBook() {
        Book originalBook = new Book("Clean Code", "Robert C. Martin", 464);
        Book clonedBook = BookCloner.cloneBook(originalBook);
        assertEquals(originalBook, clonedBook);
        assertNotSame(originalBook, clonedBook);
    }
}


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DynamicExecutor {
    public static void executeDynamicMethod(String className, String methodName, Object[] args) {
        try {
            Class<?> clazz = Class.forName(className);
            Class<?>[] parameterTypes = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                parameterTypes[i] = args[i].getClass();
            }
            Method method = clazz.getMethod(methodName, parameterTypes);
            method.invoke(null, args);
        } catch (ClassNotFoundException e) {
            System.out.println("类未找到: " + e.getMessage());
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            System.out.println("方法未找到: " + e.getMessage());
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            System.out.println("非法访问: " + e.getMessage());
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            System.out.println("调用目标异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        DynamicExecutor.executeDynamicMethod("TestMethods", "printMessage", new Object[]{"Hello, Dynamic Execution!"});
    }
}

Please write a Java method that dynamically loads and executes a specified method of a specified class. Assume we have a class named `DynamicExecutor` which contains a static method called `executeDynamicMethod`. This method takes three parameters: the first parameter is the fully qualified name of the class (including the package name), the second parameter is the name of the method to be executed, and the third parameter is an array of `Object` which are the parameters of the method. If the class or method does not exist or if any other exception occurs during execution, the method should catch these exceptions and print the stack trace rather than allowing the exception to propagate. Note that the method to be executed should be a static method and should not have a return value.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DynamicExecutor {
    public static void executeDynamicMethod(String className, String methodName, Object[] args) {
    }
}
```

import org.junit.jupiter.api.Test;
import java.lang.reflect.InvocationTargetException;
public class DynamicExecutorTest {
    @Test
    public void testExecuteDynamicMethod_validMethod() {
        Object[] args = new Object[]{"Hello, Dynamic!"};
        DynamicExecutor.executeDynamicMethod("TestMethods", "printMessage", args);
    }
    @Test
    public void testExecuteDynamicMethod_classNotFound() {
        Object[] args = new Object[]{"Hello, Dynamic!"};
        DynamicExecutor.executeDynamicMethod("NonExistentClass", "printMessage", args);
    }
    @Test
    public void testExecuteDynamicMethod_methodNotFound() {
        Object[] args = new Object[]{"Hello, Dynamic!"};
        DynamicExecutor.executeDynamicMethod("TestMethods", "nonExistentMethod", args);
    }
    @Test
    public void testExecuteDynamicMethod_illegalAccess() {
        Object[] args = new Object[]{"Hello, Dynamic!"};
        DynamicExecutor.executeDynamicMethod("TestMethods", "privateMethod", args);
    }
    @Test
    public void testExecuteDynamicMethod_invocationTargetException() {
        Object[] args = new Object[]{"Hello, Dynamic!"};
        DynamicExecutor.executeDynamicMethod("TestMethods", "exceptionThrowingMethod", args);
    }
    public static class TestMethods {
        public static void printMessage(String message) {
            System.out.println(message);
        }
        private static void privateMethod(String message) {
            System.out.println("Private: " + message);
        }
        public static void exceptionThrowingMethod(String message) throws Exception {
            throw new Exception("Test Exception");
        }
    }
}


import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimezoneConverter {
    public static String convertToUTC(String localDate, String localTime, String timezoneOffset) {
        LocalDateTime localDateTime = LocalDateTime.parse(localDate + "T" + localTime);
        ZoneOffset offset = ZoneOffset.of(fixOffsetFormat(timezoneOffset));
        OffsetDateTime offsetDateTime = localDateTime.atOffset(offset);
        ZonedDateTime utcDateTime = offsetDateTime.toZonedDateTime().withZoneSameInstant(ZoneOffset.UTC);
        return utcDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
    private static String fixOffsetFormat(String offset) {
        if (!offset.matches("^[+-]\\d{2}:\\d{2}$")) {
            return "+00:00";
        }
        return offset;
    }
    public static void main(String[] args) {
        String date = "2023-04-01";
        String time = "15:00:00";
        String offset = "+05:30";
        String utcTime = convertToUTC(date, time, offset);
        System.out.println("UTC时间: " + utcTime);
        String expectedUTC = "2023-04-01 09:30:00";
        assert utcTime.equals(expectedUTC) : "转换结果不正确";
    }
}

Please write a Java method that can convert a given date and time from a specific time zone to UTC time. The date format you need to handle is "yyyy-MM-dd", the time format is "HH:mm:ss", and the time zone offset format is "+HH:mm" or "-HH:mm". If the provided time zone offset does not match the expected format, your method should automatically correct it to ensure the conversion process does not fail due to format errors.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimezoneConverter {
    public static String convertToUTC(String localDate, String localTime, String timezoneOffset) {
    }
    private static String fixOffsetFormat(String offset) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TimezoneConverterTest {
    @Test
    public void testConvertToUTC_PositiveOffset() {
        String date = "2023-04-01";
        String time = "15:00:00";
        String offset = "+05:30";
        String result = TimezoneConverter.convertToUTC(date, time, offset);
        String expected = "2023-04-01 09:30:00";
        assertEquals(expected, result);
    }
    @Test
    public void testConvertToUTC_NegativeOffset() {
        String date = "2023-04-01";
        String time = "15:00:00";
        String offset = "-04:00";
        String result = TimezoneConverter.convertToUTC(date, time, offset);
        String expected = "2023-04-01 19:00:00";
        assertEquals(expected, result);
    }
    @Test
    public void testConvertToUTC_ZeroOffset() {
        String date = "2023-04-01";
        String time = "15:00:00";
        String offset = "+00:00";
        String result = TimezoneConverter.convertToUTC(date, time, offset);
        String expected = "2023-04-01 15:00:00";
        assertEquals(expected, result);
    }
    @Test
    public void testConvertToUTC_InvalidOffsetFormat() {
        String date = "2023-04-01";
        String time = "15:00:00";
        String offset = "invalid_offset";
        String result = TimezoneConverter.convertToUTC(date, time, offset);
        String expected = "2023-04-01 15:00:00";
        assertEquals(expected, result);
    }
    @Test
    public void testConvertToUTC_LeapYearDate() {
        String date = "2020-02-29";
        String time = "23:00:00";
        String offset = "+01:00";
        String result = TimezoneConverter.convertToUTC(date, time, offset);
        String expected = "2020-02-29 22:00:00";
        assertEquals(expected, result);
    }
}


import java.util.HashMap;
import java.util.Map;
public class RequestConfigurator {
    public static Map<String, Integer> getRequestConfig(String requestType) {
        Map<String, Integer> config = new HashMap<>();
        switch (requestType.toUpperCase()) {
            case "GET":
                config.put("timeout", 5000);
                config.put("retries", 2);
                break;
            case "POST":
                config.put("timeout", 8000);
                config.put("retries", 3);
                break;
            default:
                config.put("timeout", 3000);
                config.put("retries", 1);
                break;
        }
        return config;
    }
    public static void main(String[] args) {
        Map<String, Integer> getConfig = getRequestConfig("GET");
        System.out.println("GET请求配置：" + getConfig);
        Map<String, Integer> postConfig = getRequestConfig("POST");
        System.out.println("POST请求配置：" + postConfig);
        Map<String, Integer> defaultConfig = getRequestConfig("DELETE");
        System.out.println("默认请求配置：" + defaultConfig);
    }
}

Please design a Java method to configure the parameters of a network request. This method should be able to return the corresponding configuration object based on different request types (such as GET, POST, etc.). The configuration object should include basic information about the request, such as timeout duration, retry attempts, etc. Ensure that your code is completely standalone and 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.HashMap;
import java.util.Map;
public class RequestConfigurator {
    public static Map<String, Integer> getRequestConfig(String requestType) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Map;
import org.junit.jupiter.api.Test;
public class RequestConfiguratorTest {
    @Test
    void testGetRequestConfigWithGet() {
        Map<String, Integer> config = RequestConfigurator.getRequestConfig("GET");
        assertTrue(config.containsKey("timeout"));
        assertTrue(config.containsKey("retries"));
        assertEquals(5000, config.get("timeout"));
        assertEquals(2, config.get("retries"));
    }
    @Test
    void testGetRequestConfigWithPost() {
        Map<String, Integer> config = RequestConfigurator.getRequestConfig("POST");
        assertTrue(config.containsKey("timeout"));
        assertTrue(config.containsKey("retries"));
        assertEquals(8000, config.get("timeout"));
        assertEquals(3, config.get("retries"));
    }
    @Test
    void testGetRequestConfigWithUnknownType() {
        Map<String, Integer> config = RequestConfigurator.getRequestConfig("DELETE");
        assertTrue(config.containsKey("timeout"));
        assertTrue(config.containsKey("retries"));
        assertEquals(3000, config.get("timeout"));
        assertEquals(1, config.get("retries"));
    }
    @Test
    void testGetRequestConfigCaseInsensitive() {
        Map<String, Integer> config = RequestConfigurator.getRequestConfig("get");
        assertTrue(config.containsKey("timeout"));
        assertTrue(config.containsKey("retries"));
        assertEquals(5000, config.get("timeout"));
        assertEquals(2, config.get("retries"));
    }
    @Test
    void testGetRequestConfigEmptyType() {
        Map<String, Integer> config = RequestConfigurator.getRequestConfig("");
        assertTrue(config.containsKey("timeout"));
        assertTrue(config.containsKey("retries"));
        assertEquals(3000, config.get("timeout"));
        assertEquals(1, config.get("retries"));
    }
}


import java.util.HashMap;
import java.util.Map;
class StudentInfo {
    String name;
    int age;
    String major;
    public StudentInfo(String name, int age, String major) {
        this.name = name;
        this.age = age;
        this.major = major;
    }
    @Override
    public String toString() {
        return "姓名: " + name + ", 年龄: " + age + ", 专业: " + major;
    }
}
public class StudentDatabase {
    private static Map<Long, StudentInfo> studentDB = new HashMap<>();
    static {
        studentDB.put(1L, new StudentInfo("张三", 20, "计算机科学与技术"));
        studentDB.put(2L, new StudentInfo("李四", 22, "软件工程"));
        studentDB.put(3L, new StudentInfo("王五", 19, "信息安全"));
    }
    public static StudentInfo getStudentDetails(Long studentId) {
        if (studentDB.containsKey(studentId)) {
            return studentDB.get(studentId);
        } else {
            return null;
        }
    }
    public static void main(String[] args) {
        System.out.println(getStudentDetails(1L));
        System.out.println(getStudentDetails(4L));
    }
}

Write a Java method that accepts a student's ID as a parameter and then returns the student's detailed information. If the student's information does not exist in the database, the method should return null.
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;
class StudentInfo {
    String name;
    int age;
    String major;
    public StudentInfo(String name, int age, String major) {
    }
    @Override
    public String toString() {
    }
}
public class StudentDatabase {
    private static Map<Long, StudentInfo> studentDB = new HashMap<>();
    static {
        studentDB.put(1L, new StudentInfo("张三", 20, "计算机科学与技术"));
        studentDB.put(2L, new StudentInfo("李四", 22, "软件工程"));
        studentDB.put(3L, new StudentInfo("王五", 19, "信息安全"));
    }
    public static StudentInfo getStudentDetails(Long studentId) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StudentInfoTest {
}
class StudentDatabaseTest {
    @Test
    void testGetStudentDetails_existingStudent() {
        StudentInfo student = StudentDatabase.getStudentDetails(1L);
        assertNotNull(student);
        assertEquals("张三", student.name);
        assertEquals(20, student.age);
        assertEquals("计算机科学与技术", student.major);
    }
    @Test
    void testGetStudentDetails_nonExistingStudent() {
        StudentInfo student = StudentDatabase.getStudentDetails(4L);
        assertNull(student);
    }
    @Test
    void testGetStudentDetails_anotherExistingStudent() {
        StudentInfo student = StudentDatabase.getStudentDetails(2L);
        assertNotNull(student);
        assertEquals("李四", student.name);
        assertEquals(22, student.age);
        assertEquals("软件工程", student.major);
    }
    @Test
    void testGetStudentDetails_yetAnotherExistingStudent() {
        StudentInfo student = StudentDatabase.getStudentDetails(3L);
        assertNotNull(student);
        assertEquals("王五", student.name);
        assertEquals(19, student.age);
        assertEquals("信息安全", student.major);
    }
    @Test
    void testGetStudentDetails_nullInput() {
        StudentInfo student = StudentDatabase.getStudentDetails(null);
        assertNull(student);
    }
}


import java.util.HashMap;
public class StudentRegistrationValidator {
    public static boolean isRegistrationComplete(HashMap<String, String> studentInfo) {
        String[] requiredKeys = {"姓名", "学号", "专业", "年级", "邮箱", "手机号"};
        for (String key : requiredKeys) {
            if (!studentInfo.containsKey(key)) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        HashMap<String, String> studentInfo = new HashMap<>();
        studentInfo.put("姓名", "张三");
        studentInfo.put("学号", "123456");
        studentInfo.put("专业", "计算机科学与技术");
        studentInfo.put("年级", "大三");
        studentInfo.put("邮箱", "zhangsan@example.com");
        studentInfo.put("手机号", "13800000000");
        boolean isComplete = isRegistrationComplete(studentInfo);
        System.out.println("注册信息是否完整: " + isComplete);
    }
}

Please design a Java function to verify whether the registration information of a student in a student information system is complete. The registration information includes the student's name, student ID, major, grade, email, and phone number. The information is stored in the form of key-value pairs in a class named `StudentInfo`. Make sure all necessary keys are present, and their order can be arbitrary.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
public class StudentRegistrationValidator {
    public static boolean isRegistrationComplete(HashMap<String, String> studentInfo) {
    }
}
```

import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
public class StudentRegistrationValidatorTest {
    @Test
    public void testCompleteRegistration() {
        HashMap<String, String> studentInfo = new HashMap<>();
        studentInfo.put("姓名", "张三");
        studentInfo.put("学号", "123456");
        studentInfo.put("专业", "计算机科学与技术");
        studentInfo.put("年级", "大三");
        studentInfo.put("邮箱", "zhangsan@example.com");
        studentInfo.put("手机号", "13800000000");
        assertTrue(StudentRegistrationValidator.isRegistrationComplete(studentInfo));
    }
    @Test
    public void testIncompleteRegistrationMissingName() {
        HashMap<String, String> studentInfo = new HashMap<>();
        studentInfo.put("学号", "123456");
        studentInfo.put("专业", "计算机科学与技术");
        studentInfo.put("年级", "大三");
        studentInfo.put("邮箱", "zhangsan@example.com");
        studentInfo.put("手机号", "13800000000");
        assertFalse(StudentRegistrationValidator.isRegistrationComplete(studentInfo));
    }
    @Test
    public void testIncompleteRegistrationMissingEmail() {
        HashMap<String, String> studentInfo = new HashMap<>();
        studentInfo.put("姓名", "张三");
        studentInfo.put("学号", "123456");
        studentInfo.put("专业", "计算机科学与技术");
        studentInfo.put("年级", "大三");
        studentInfo.put("手机号", "13800000000");
        assertFalse(StudentRegistrationValidator.isRegistrationComplete(studentInfo));
    }
    @Test
    public void testIncompleteRegistrationEmptyFields() {
        HashMap<String, String> studentInfo = new HashMap<>();
        studentInfo.put("姓名", "");
        studentInfo.put("学号", "");
        studentInfo.put("专业", "");
        studentInfo.put("年级", "");
        studentInfo.put("邮箱", "");
        studentInfo.put("手机号", "");
        assertTrue(StudentRegistrationValidator.isRegistrationComplete(studentInfo));
    }
    @Test
    public void testIncompleteRegistrationExtraFields() {
        HashMap<String, String> studentInfo = new HashMap<>();
        studentInfo.put("姓名", "张三");
        studentInfo.put("学号", "123456");
        studentInfo.put("专业", "计算机科学与技术");
        studentInfo.put("年级", "大三");
        studentInfo.put("邮箱", "zhangsan@example.com");
        studentInfo.put("手机号", "13800000000");
        studentInfo.put("地址", "北京市");
        assertTrue(StudentRegistrationValidator.isRegistrationComplete(studentInfo));
    }
}


import java.util.HashMap;
import java.util.Map;
public class UserTaskManager {
    private Map<Integer, Integer> userTasks;
    public UserTaskManager() {
        userTasks = new HashMap<>();
    }
    public void updateTaskId(int userId, int taskId) {
        userTasks.put(userId, taskId);
    }
    public boolean checkTaskId(int userId, int expectedTaskId) {
        if (userTasks.containsKey(userId)) {
            return userTasks.get(userId) == expectedTaskId;
        }
        return false;
    }
    public static void main(String[] args) {
        UserTaskManager manager = new UserTaskManager();
        manager.updateTaskId(1, 100);
        manager.updateTaskId(2, 200);
        System.out.println("检查用户1的任务ID是否更新为100: " + manager.checkTaskId(1, 100));
        System.out.println("检查用户2的任务ID是否更新为200: " + manager.checkTaskId(2, 200));
    }
}

Please design a Java method that is used to update the user's task ID. The task ID is an integer used to identify the user's current task.
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 UserTaskManager {
    private Map<Integer, Integer> userTasks;
    public UserTaskManager() {
    }
    public void updateTaskId(int userId, int taskId) {
    }
    public boolean checkTaskId(int userId, int expectedTaskId) {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
public class UserTaskManagerTest {
    @Test
    public void testUpdateTaskId_NewUser() {
        UserTaskManager manager = new UserTaskManager();
        manager.updateTaskId(1, 100);
        assertTrue(manager.checkTaskId(1, 100));
    }
    @Test
    public void testUpdateTaskId_ExistingUser() {
        UserTaskManager manager = new UserTaskManager();
        manager.updateTaskId(1, 100);
        manager.updateTaskId(1, 200);
        assertTrue(manager.checkTaskId(1, 200));
    }
    @Test
    public void testCheckTaskId_CorrectTaskId() {
        UserTaskManager manager = new UserTaskManager();
        manager.updateTaskId(1, 100);
        assertTrue(manager.checkTaskId(1, 100));
    }
    @Test
    public void testCheckTaskId_IncorrectTaskId() {
        UserTaskManager manager = new UserTaskManager();
        manager.updateTaskId(1, 100);
        assertFalse(manager.checkTaskId(1, 200));
    }
    @Test
    public void testCheckTaskId_UserDoesNotExist() {
        UserTaskManager manager = new UserTaskManager();
        assertFalse(manager.checkTaskId(1, 100));
    }
}


import java.lang.Class;
public class ClassLoaderChecker {
    public static boolean canLoadClass(String className) {
        try {
            Class.forName(className);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
    public static void main(String[] args) {
        String testClassName1 = "java.lang.String";
        String testClassName2 = "com.unknown.NonExistentClass";
        System.out.println("Can load " + testClassName1 + ": " + canLoadClass(testClassName1));
        System.out.println("Can load " + testClassName2 + ": " + canLoadClass(testClassName2));
    }
}

Please describe the task of the function that checks if a given class name can be successfully loaded. If the given class name can be successfully loaded, the function should return `true`; otherwise, it should return `false`. Ensure that the function can handle any exceptions to prevent crashing.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.Class;
public class ClassLoaderChecker {
    public static boolean canLoadClass(String className) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class ClassLoaderCheckerTest {
    @Test
    public void testCanLoadExistingClass() {
        assertTrue(ClassLoaderChecker.canLoadClass("java.lang.String"));
    }
    @Test
    public void testCannotLoadNonExistentClass() {
        assertFalse(ClassLoaderChecker.canLoadClass("com.unknown.NonExistentClass"));
    }
    @Test
    public void testCanLoadAnotherExistingClass() {
        assertTrue(ClassLoaderChecker.canLoadClass("java.util.ArrayList"));
    }
    @Test
    public void testCannotLoadIncorrectClassName() {
        assertFalse(ClassLoaderChecker.canLoadClass("incorrect.ClassName"));
    }
    @Test
    public void testCanLoadPrimitiveType() {
        assertFalse(ClassLoaderChecker.canLoadClass("int"));
    }
}


import java.lang.IllegalArgumentException;
public class StudentRegistrationValidator {
    public static void validateStudentInput(StudentDto studentDto) {
        String name = studentDto.getName();
        Integer age = studentDto.getAge();
        Integer grade = studentDto.getGrade();
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("学生姓名不能为空。");
        }
        if (age == null || age < 6 || age > 18) {
            throw new IllegalArgumentException("学生年龄必须在6到18岁之间。");
        }
        if (grade == null || grade < 1 || grade > 12) {
            throw new IllegalArgumentException("学生班级必须在1到12之间。");
        }
    }
    public static void main(String[] args) {
        StudentDto student1 = new StudentDto("张三", 15, 9);
        StudentDto student2 = new StudentDto("", 20, 5);
        StudentDto student3 = new StudentDto("李四", 7, 0);
        try {
            validateStudentInput(student1);
            System.out.println("学生1验证通过。");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
        try {
            validateStudentInput(student2);
            System.out.println("学生2验证通过。");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
        try {
            validateStudentInput(student3);
            System.out.println("学生3验证通过。");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
class StudentDto {
    private String name;
    private Integer age;
    private Integer grade;
    public StudentDto(String name, Integer age, Integer grade) {
        this.name = name;
        this.age = age;
        this.grade = grade;
    }
    public String getName() {
        return name;
    }
    public Integer getAge() {
        return age;
    }
    public Integer getGrade() {
        return grade;
    }
}

Please design a Java function to validate student registration information. The student information includes name, age, and class. The name cannot be empty, the age should be between 6 and 18 years old, and the class should be an integer between 1 and 12. If any of these conditions are not met, an IllegalArgumentException should be thrown with an appropriate error 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 StudentRegistrationValidator {
    public static void validateStudentInput(StudentDto studentDto) {
    }
}
class StudentDto {
    private String name;
    private Integer age;
    private Integer grade;
    public StudentDto(String name, Integer age, Integer grade) {
    }
    public String getName() {
        return name;
    }
    public Integer getAge() {
        return age;
    }
    public Integer getGrade() {
        return grade;
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.rules.ExpectedException;
import org.junit.Rule;
public class StudentRegistrationValidatorTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();
    @Test
    public void testValidateStudentInput_withValidInput() {
        StudentDto validStudent = new StudentDto("张三", 15, 9);
        StudentRegistrationValidator.validateStudentInput(validStudent);
    }
    @Test
    public void testValidateStudentInput_withEmptyName() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("学生姓名不能为空。");
        StudentDto studentWithEmptyName = new StudentDto("", 15, 9);
        StudentRegistrationValidator.validateStudentInput(studentWithEmptyName);
    }
    @Test
    public void testValidateStudentInput_withNullName() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("学生姓名不能为空。");
        StudentDto studentWithNullName = new StudentDto(null, 15, 9);
        StudentRegistrationValidator.validateStudentInput(studentWithNullName);
    }
    @Test
    public void testValidateStudentInput_withInvalidAge() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("学生年龄必须在6到18岁之间。");
        StudentDto studentWithInvalidAge = new StudentDto("李四", 5, 9);
        StudentRegistrationValidator.validateStudentInput(studentWithInvalidAge);
    }
    @Test
    public void testValidateStudentInput_withInvalidGrade() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("学生班级必须在1到12之间。");
        StudentDto studentWithInvalidGrade = new StudentDto("王五", 15, 13);
        StudentRegistrationValidator.validateStudentInput(studentWithInvalidGrade);
    }
}


import java.time.LocalDateTime;
public class MessageDetails {
    String sender;
    String receiver;
    String serviceType;
    String messageType;
    String messageId;
    LocalDateTime creationTime;
    boolean isDuplicated;
    public void cloneTo(MessageDetails target) {
        target.sender = this.sender;
        target.receiver = this.receiver;
        target.serviceType = this.serviceType;
        target.messageType = this.messageType;
        target.messageId = this.messageId;
        target.creationTime = this.creationTime;
        target.isDuplicated = this.isDuplicated;
    }
    public static void main(String[] args) {
        MessageDetails original = new MessageDetails();
        original.sender = "Alice";
        original.receiver = "Bob";
        original.serviceType = "Email";
        original.messageType = "Greeting";
        original.messageId = "12345";
        original.creationTime = LocalDateTime.now();
        original.isDuplicated = false;
        MessageDetails cloned = new MessageDetails();
        original.cloneTo(cloned);
        System.out.println("Sender matches: " + original.sender.equals(cloned.sender));
        System.out.println("Receiver matches: " + original.receiver.equals(cloned.receiver));
        System.out.println("ServiceType matches: " + original.serviceType.equals(cloned.serviceType));
        System.out.println("MessageType matches: " + original.messageType.equals(cloned.messageType));
        System.out.println("MessageId matches: " + original.messageId.equals(cloned.messageId));
        System.out.println("CreationTime matches: " + original.creationTime.equals(cloned.creationTime));
        System.out.println("IsDuplicated matches: " + (original.isDuplicated == cloned.isDuplicated));
    }
}

Please design a Java class `MessageDetails`, which includes several attributes: `sender`, `receiver`, `serviceType`, `messageType`, `messageId`, `creationTime`, and `isDuplicated`. You need to implement a method `cloneTo`, which accepts another `MessageDetails` object as a parameter and copies all the attributes of the current object to the parameter object.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.time.LocalDateTime;
public class MessageDetails {
    String sender;
    String receiver;
    String serviceType;
    String messageType;
    String messageId;
    LocalDateTime creationTime;
    boolean isDuplicated;
    public void cloneTo(MessageDetails target) {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
public class MessageDetailsTest {
    private MessageDetails original;
    private MessageDetails cloned;
    @BeforeEach
    public void setUp() {
        original = new MessageDetails();
        original.sender = "Alice";
        original.receiver = "Bob";
        original.serviceType = "Email";
        original.messageType = "Greeting";
        original.messageId = "12345";
        original.creationTime = LocalDateTime.now();
        original.isDuplicated = false;
        cloned = new MessageDetails();
    }
    @Test
    public void testCloneToSender() {
        original.cloneTo(cloned);
        assertEquals(original.sender, cloned.sender);
    }
    @Test
    public void testCloneToReceiver() {
        original.cloneTo(cloned);
        assertEquals(original.receiver, cloned.receiver);
    }
    @Test
    public void testCloneToServiceType() {
        original.cloneTo(cloned);
        assertEquals(original.serviceType, cloned.serviceType);
    }
    @Test
    public void testCloneToMessageType() {
        original.cloneTo(cloned);
        assertEquals(original.messageType, cloned.messageType);
    }
    @Test
    public void testCloneToAllFields() {
        original.cloneTo(cloned);
        assertEquals(original.messageId, cloned.messageId);
        assertEquals(original.creationTime, cloned.creationTime);
        assertEquals(original.isDuplicated, cloned.isDuplicated);
    }
}


import java.io.StringWriter;
import java.io.PrintWriter;
import java.net.UnknownHostException;
public class ExceptionStackTraceHelper {
    public static String getExceptionStackTrace(Throwable exception) {
        if (exception == null) {
            return "";
        }
        Throwable currentException = exception;
        while (currentException != null) {
            if (currentException instanceof UnknownHostException) {
                return "";
            }
            currentException = currentException.getCause();
        }
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        exception.printStackTrace(printWriter);
        printWriter.flush();
        return stringWriter.toString();
    }
    public static void main(String[] args) {
        try {
            throw new Exception("测试异常");
        } catch (Exception e) {
            System.out.println(getExceptionStackTrace(e));
        }
        try {
            throw new UnknownHostException("未知主机");
        } catch (Exception e) {
            System.out.println(getExceptionStackTrace(e).equals("") ? "测试通过: UnknownHostException" : "测试失败");
        }
    }
}

Please write a Java method that accepts an exception object as a parameter and returns the stack trace information of that exception as a string representation. If the passed exception object is `null`, or if the exception or any of its cause chain contains an `UnknownHostException`, the method should return an empty string. Ensure that your method can handle all the exceptions in the chain and check for the presence of `UnknownHostException` before returning the stack trace information.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.io.StringWriter;
import java.io.PrintWriter;
import java.net.UnknownHostException;
public class ExceptionStackTraceHelper {
    public static String getExceptionStackTrace(Throwable exception) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;
import org.junit.jupiter.api.Test;
public class ExceptionStackTraceHelperTest {
    @Test
    public void testGetExceptionStackTrace_NullException() {
        String result = ExceptionStackTraceHelper.getExceptionStackTrace(null);
        assertEquals("", result);
    }
    @Test
    public void testGetExceptionStackTrace_UnknownHostException() {
        UnknownHostException unknownHostException = new UnknownHostException("测试未知主机异常");
        String result = ExceptionStackTraceHelper.getExceptionStackTrace(unknownHostException);
        assertEquals("", result);
    }
    @Test
    public void testGetExceptionStackTrace_GenericException() {
        Exception exception = new Exception("测试异常");
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        exception.printStackTrace(printWriter);
        printWriter.flush();
        String expected = stringWriter.toString();
        String result = ExceptionStackTraceHelper.getExceptionStackTrace(exception);
        assertEquals(expected, result);
    }
    @Test
    public void testGetExceptionStackTrace_CausedByUnknownHostException() {
        Exception exception = new Exception("外部异常", new UnknownHostException("内部未知主机异常"));
        String result = ExceptionStackTraceHelper.getExceptionStackTrace(exception);
        assertEquals("", result);
    }
    @Test
    public void testGetExceptionStackTrace_CausedByOtherException() {
        Exception cause = new Exception("内部异常");
        Exception exception = new Exception("外部异常", cause);
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        exception.printStackTrace(printWriter);
        printWriter.flush();
        String expected = stringWriter.toString();
        String result = ExceptionStackTraceHelper.getExceptionStackTrace(exception);
        assertEquals(expected, result);
    }
}


import java.util.HashMap;
import java.util.Map;
public class BookQuerySystem {
    private Map<String, String> bookDatabase = new HashMap<>();
    public BookQuerySystem() {
        bookDatabase.put("001", "《Java编程思想》");
        bookDatabase.put("002", "《Effective Java》");
        bookDatabase.put("003", "《Spring实战》");
    }
    public String queryBookDetail(String bookId) throws BookNotFoundException {
        if (!bookDatabase.containsKey(bookId)) {
            throw new BookNotFoundException("图书ID不存在: " + bookId);
        }
        return bookDatabase.get(bookId);
    }
    static class BookNotFoundException extends Exception {
        public BookNotFoundException(String message) {
            super(message);
        }
    }
    public static void main(String[] args) {
        BookQuerySystem system = new BookQuerySystem();
        try {
            String bookDetail = system.queryBookDetail("002");
            System.out.println("查询成功: " + bookDetail);
        } catch (BookNotFoundException e) {
            System.err.println(e.getMessage());
        }
    }
}

Assume you are developing a library management system and need to implement a feature to query detailed information about a book. Given a book ID, you need to return the detailed information of the book. If the book ID does not exist, a custom exception should be thrown. Please design this feature.
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 BookQuerySystem {
    private Map<String, String> bookDatabase = new HashMap<>();
    public BookQuerySystem() {
    }
    public String queryBookDetail(String bookId) throws BookNotFoundException {
    }
    static class BookNotFoundException extends Exception {
        public BookNotFoundException(String message) {
        }
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap;
import java.util.Map;
public class BookQuerySystemTest {
    @Test
    void testQueryBookDetailExistingId() throws BookQuerySystem.BookNotFoundException {
        BookQuerySystem system = new BookQuerySystem();
        String result = system.queryBookDetail("001");
        assertEquals("《Java编程思想》", result);
    }
    @Test
    void testQueryBookDetailNonExistingId() {
        BookQuerySystem system = new BookQuerySystem();
        assertThrows(BookQuerySystem.BookNotFoundException.class, () -> {
            system.queryBookDetail("999");
        });
    }
    @Test
    void testQueryBookDetailAnotherExistingId() throws BookQuerySystem.BookNotFoundException {
        BookQuerySystem system = new BookQuerySystem();
        String result = system.queryBookDetail("002");
        assertEquals("《Effective Java》", result);
    }
    @Test
    void testQueryBookDetailEmptyId() {
        BookQuerySystem system = new BookQuerySystem();
        assertThrows(BookQuerySystem.BookNotFoundException.class, () -> {
            system.queryBookDetail("");
        });
    }
    @Test
    void testQueryBookDetailNullId() {
        BookQuerySystem system = new BookQuerySystem();
        assertThrows(BookQuerySystem.BookNotFoundException.class, () -> {
            system.queryBookDetail(null);
        });
    }
}


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 String divide(double a, double b) {
        if (b == 0) {
            return "错误：除数不能为0。";
        }
        return Double.toString(a / b);
    }
    public static void main(String[] args) {
        SimpleCalculator calculator = new SimpleCalculator();
        System.out.println("10 + 5 = " + calculator.add(10, 5));
        System.out.println("20 - 10 = " + calculator.subtract(20, 10));
        System.out.println("10 * 5 = " + calculator.multiply(10, 5));
        System.out.println("10 / 2 = " + calculator.divide(10, 2));
        System.out.println("10 / 0 = " + calculator.divide(10, 0));
    }
}

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. Make sure your program can handle division by zero, and when attempting to divide by zero, it should return a specific error message instead of crashing. Please follow these guidelines to complete this task:

- Do not use any external libraries.
- Ensure the code is self-contained and clear.
- Use appropriate variable names and function names to make the code easy to understand.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
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 String divide(double a, double b) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class SimpleCalculatorTest {
    @Test
    public void testAdd() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(15, calculator.add(10, 5));
        assertEquals(0, calculator.add(-1, 1));
        assertEquals(-3, calculator.add(-1.5, -1.5));
    }
    @Test
    public void testSubtract() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(10, calculator.subtract(20, 10));
        assertEquals(0, calculator.subtract(5, 5));
        assertEquals(-1, calculator.subtract(1, 2));
    }
    @Test
    public void testMultiply() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(50, calculator.multiply(10, 5));
        assertEquals(0, calculator.multiply(10, 0));
        assertEquals(-10, calculator.multiply(10, -1));
    }
    @Test
    public void testDivide() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals("5.0", calculator.divide(10, 2));
        assertEquals("错误：除数不能为0。", calculator.divide(10, 0));
        assertEquals("-5.0", calculator.divide(10, -2));
    }
    @Test
    public void testDivideByZeroException() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals("错误：除数不能为0。", calculator.divide(10, 0));
    }
}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
public class ReverseFileContent {
    public static void reversePrint(String filePath) throws FileNotFoundException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在: " + filePath);
        }
        Stack<String> lines = new Stack<>();
        try (Scanner scanner = new Scanner(file)) {
            while (scanner.hasNextLine()) {
                lines.push(scanner.nextLine());
            }
        }
        while (!lines.isEmpty()) {
            System.out.println(lines.pop());
        }
    }
    public static void main(String[] args) {
        try {
            reversePrint("path/to/your/textfile.txt");
        } catch (FileNotFoundException e) {
            System.err.println(e.getMessage());
        }
    }
}

Please write a Java program to implement a simple reverse output function for the content of a text file. Given the path of a text file, you need to read its content and reverse the content of each line, then output it to the console. Make sure that your program can handle possible exceptions that may occur during file reading, and check whether the file exists before reading it.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
public class ReverseFileContent {
    public static void reversePrint(String filePath) throws FileNotFoundException {
    }
}
```

import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Stack;
import java.util.Scanner;
public class ReverseFileContentTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();
    @Test
    public void testReversePrint_FileNotFound() throws FileNotFoundException {
        thrown.expect(FileNotFoundException.class);
        thrown.expectMessage("文件不存在: invalid/path/to/textfile.txt");
        ReverseFileContent.reversePrint("invalid/path/to/textfile.txt");
    }
    @Test
    public void testReversePrint_EmptyFile() throws FileNotFoundException {
        File tempFile = new File("empty.txt");
        try (PrintWriter writer = new PrintWriter(tempFile)) {
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReverseFileContent.reversePrint("empty.txt");
        tempFile.delete();
    }
    @Test
    public void testReversePrint_SingleLineFile() throws FileNotFoundException {
        File tempFile = new File("singleline.txt");
        try (PrintWriter writer = new PrintWriter(tempFile)) {
            writer.println("single line");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReverseFileContent.reversePrint("singleline.txt");
        tempFile.delete();
    }
    @Test
    public void testReversePrint_MultiLineFile() throws FileNotFoundException {
        File tempFile = new File("multiline.txt");
        try (PrintWriter writer = new PrintWriter(tempFile)) {
            writer.println("line 1");
            writer.println("line 2");
            writer.println("line 3");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReverseFileContent.reversePrint("multiline.txt");
        tempFile.delete();
    }
    @Test
    public void testReversePrint_FileWithBlankLines() throws FileNotFoundException {
        File tempFile = new File("filewithblanks.txt");
        try (PrintWriter writer = new PrintWriter(tempFile)) {
            writer.println("line 1");
            writer.println("");
            writer.println("line 2");
            writer.println("");
            writer.println("line 3");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReverseFileContent.reversePrint("filewithblanks.txt");
        tempFile.delete();
    }
}


import java.util.Date;
public class ParkingDurationCalculator {
    public static int calculateParkingDuration(Date arrival, Date departure) {
        if (departure.before(arrival)) {
            return -1;
        }
        long durationInMillis = departure.getTime() - arrival.getTime();
        return (int) (durationInMillis / (1000 * 60 * 60));
    }
    public static void main(String[] args) {
        Date arrival = new Date(120, 5, 20, 8, 0);
        Date departure = new Date(120, 5, 20, 12, 0);
        System.out.println("停车时长（小时）: " + calculateParkingDuration(arrival, departure));
        Date earlyDeparture = new Date(120, 5, 20, 7, 0);
        System.out.println("停车时长（小时）: " + calculateParkingDuration(arrival, earlyDeparture));
    }
}

Please write a Java program to calculate the parking time. Suppose you have a parking lot management system that needs to calculate the parking duration based on the vehicle's arrival and departure times. You need to implement a method that accepts two parameters: the vehicle's arrival time and departure time, both of which are of type `java.util.Date`. Your task is to calculate and return the vehicle's parking duration in hours, ignoring time below minutes. If the departure time is earlier than the arrival time, return -1 to indicate an error.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Date;
public class ParkingDurationCalculator {
    public static int calculateParkingDuration(Date arrival, Date departure) {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
import java.util.Date;
public class ParkingDurationCalculatorTest {
    @Test
    public void testCalculateParkingDuration_sameTime() {
        Date arrival = new Date(120, 5, 20, 8, 0);
        Date departure = new Date(120, 5, 20, 8, 0);
        int result = ParkingDurationCalculator.calculateParkingDuration(arrival, departure);
        assertEquals(0, result);
    }
    @Test
    public void testCalculateParkingDuration_positiveDuration() {
        Date arrival = new Date(120, 5, 20, 8, 0);
        Date departure = new Date(120, 5, 20, 12, 0);
        int result = ParkingDurationCalculator.calculateParkingDuration(arrival, departure);
        assertEquals(4, result);
    }
    @Test
    public void testCalculateParkingDuration_negativeDuration() {
        Date arrival = new Date(120, 5, 20, 8, 0);
        Date departure = new Date(120, 5, 20, 7, 0);
        int result = ParkingDurationCalculator.calculateParkingDuration(arrival, departure);
        assertEquals(-1, result);
    }
    @Test
    public void testCalculateParkingDuration_partHourDuration() {
        Date arrival = new Date(120, 5, 20, 8, 0);
        Date departure = new Date(120, 5, 20, 10, 30);
        int result = ParkingDurationCalculator.calculateParkingDuration(arrival, departure);
        assertEquals(2, result);
    }
    @Test
    public void testCalculateParkingDuration_exactHourBoundary() {
        Date arrival = new Date(120, 5, 20, 8, 0);
        Date departure = new Date(120, 5, 20, 10, 0);
        int result = ParkingDurationCalculator.calculateParkingDuration(arrival, departure);
        assertEquals(2, result);
    }
}


Please write a Java program to verify if the domain part of a URL is valid. A domain is considered invalid if it contains special characters, such as a question mark (?). You need to implement a method called `checkDomainValidity`, which takes a string parameter representing the domain and returns a boolean value indicating whether the domain is valid. A valid domain returns `true`, while a domain that contains special characters returns `false`.

Make sure your code includes a class called `DomainValidator` and a static method called `checkDomainValidity`.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.regex.Pattern;
public class DomainValidator {
    public static boolean checkDomainValidity(String domain) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.regex.Pattern;
public class DomainValidator {
    public static boolean checkDomainValidity(String domain) {
        Pattern pattern = Pattern.compile("[?]");
        return !pattern.matcher(domain).find();
    }
    public static void main(String[] args) {
        String[] testDomains = {"example.com", "invalid?domain.com", "another.valid-domain.com", "invalid.domain?com"};
        for (String domain : testDomains) {
            boolean isValid = checkDomainValidity(domain);
            System.out.println("域名 \"" + domain + "\" 是否有效: " + isValid);
        }
    }
}
class DomainValidatorTest {
    @Test
    public void testValidDomain1() {
        assertTrue(DomainValidator.checkDomainValidity("example.com"));
    }
    @Test
    public void testValidDomain2() {
        assertTrue(DomainValidator.checkDomainValidity("another.valid-domain.com"));
    }
    @Test
    public void testInvalidDomain1() {
        assertFalse(DomainValidator.checkDomainValidity("invalid?domain.com"));
    }
    @Test
    public void testInvalidDomain2() {
        assertFalse(DomainValidator.checkDomainValidity("invalid.domain?com"));
    }
    @Test
    public void testValidDomainWithSubdomain() {
        assertTrue(DomainValidator.checkDomainValidity("sub.example.com"));
    }
}


import java.util.Arrays;
public class PropertyRenamer {
    public String[] renameProperty(NameTransformer transformer, String[] propertyNames) {
        if (transformer == null || propertyNames == null) {
            return propertyNames;
        }
        String[] transformedNames = new String[propertyNames.length];
        for (int i = 0; i < propertyNames.length; i++) {
            transformedNames[i] = transformer.transform(propertyNames[i]);
        }
        return transformedNames;
    }
    public void checkFunction(String[] originalNames, String[] expectedNames, NameTransformer transformer) {
        String[] result = renameProperty(transformer, originalNames);
        if (Arrays.equals(result, expectedNames)) {
            System.out.println("转换正确！");
        } else {
            System.out.println("转换错误，期望的结果是：" + Arrays.toString(expectedNames) + "，但实际结果是：" + Arrays.toString(result));
        }
    }
}

Please write a Java class `PropertyRenamer` that includes a method `renameProperty`, which takes a property name transformer `NameTransformer` and an array of property names `propertyNames`. The purpose of this method is to use the `NameTransformer` to transform each property name in the `propertyNames` array and return a new array containing the transformed property names. Ensure that your code can handle the cases where the transformer or the property names array is null.

Below is a simple `NameTransformer` interface and an implementation example that you can use to test your `PropertyRenamer` class:

```java
import java.util.Arrays;

interface NameTransformer {
    String transform(String propertyName);
}

class PrefixNameTransformer implements NameTransformer {
    private String prefix;

    public PrefixNameTransformer(String prefix) {
        this.prefix = prefix;
    }

    @Override
    public String transform(String propertyName) {
        return prefix + propertyName;
    }
}

public class PropertyRenamer {
    // TODO: Implement the renameProperty method
}
```
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Arrays;
public class PropertyRenamer {
    public String[] renameProperty(NameTransformer transformer, String[] propertyNames) {
    }
    public void checkFunction(String[] originalNames, String[] expectedNames, NameTransformer transformer) {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
public class PropertyRenamerTest {
    @Test
    public void testRenameProperty_withValidTransformerAndPropertyNames() {
        PropertyRenamer renamer = new PropertyRenamer();
        NameTransformer transformer = new NameTransformer() {
            public String transform(String name) {
                return name.toUpperCase();
            }
        };
        String[] propertyNames = {"name", "address", "email"};
        String[] expectedNames = {"NAME", "ADDRESS", "EMAIL"};
        assertArrayEquals(expectedNames, renamer.renameProperty(transformer, propertyNames));
    }
    @Test
    public void testRenameProperty_withNullTransformer() {
        PropertyRenamer renamer = new PropertyRenamer();
        String[] propertyNames = {"name", "address", "email"};
        assertArrayEquals(propertyNames, renamer.renameProperty(null, propertyNames));
    }
    @Test
    public void testRenameProperty_withNullPropertyNames() {
        PropertyRenamer renamer = new PropertyRenamer();
        NameTransformer transformer = new NameTransformer() {
            public String transform(String name) {
                return name.toUpperCase();
            }
        };
        assertNull(renamer.renameProperty(transformer, null));
    }
    @Test
    public void testRenameProperty_withEmptyPropertyNames() {
        PropertyRenamer renamer = new PropertyRenamer();
        NameTransformer transformer = new NameTransformer() {
            public String transform(String name) {
                return name.toUpperCase();
            }
        };
        String[] propertyNames = {};
        String[] expectedNames = {};
        assertArrayEquals(expectedNames, renamer.renameProperty(transformer, propertyNames));
    }
    @Test
    public void testRenameProperty_withValidTransformerAndMixedPropertyNames() {
        PropertyRenamer renamer = new PropertyRenamer();
        NameTransformer transformer = new NameTransformer() {
            public String transform(String name) {
                return name.toUpperCase();
            }
        };
        String[] propertyNames = {"name", "", "email"};
        String[] expectedNames = {"NAME", "", "EMAIL"};
        assertArrayEquals(expectedNames, renamer.renameProperty(transformer, propertyNames));
    }
}
interface NameTransformer {
    String transform(String name);
}


import java.util.ArrayList;
import java.util.List;
class Book {
    private String title;
    private String author;
    private String isbn;
    private int year;
    public Book(String title, String author, String isbn, int year) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
        this.year = year;
    }
    public String getTitle() {
        return title;
    }
    public String getAuthor() {
        return author;
    }
    public String getIsbn() {
        return isbn;
    }
    public int getYear() {
        return year;
    }
}
class BookReader {
    public static List<Book> getAll() {
        List<Book> books = new ArrayList<>();
        books.add(new Book("Java编程思想", "Bruce Eckel", "978-0131872486", 2006));
        books.add(new Book("Effective Java", "Joshua Bloch", "978-0134685991", 2018));
        return books;
    }
}
public class LibraryDisplay {
    private static final int WIDTH = 50;
    public static void displayAllBooks() {
        List<Book> books = BookReader.getAll();
        if (!books.isEmpty()) {
            System.out.println("----DISPLAYING ALL BOOKS----");
            for (Book book : books) {
                for (int i = 0; i < WIDTH; i++)
                    System.out.print("-");
                System.out.print("\n");
                System.out.println("TITLE: " + book.getTitle());
                System.out.println("AUTHOR: " + book.getAuthor());
                System.out.println("ISBN: " + book.getIsbn());
                System.out.println("YEAR: " + book.getYear());
                for (int i = 0; i < WIDTH; i++)
                    System.out.print("-");
                System.out.print("\n");
            }
        } else {
            System.out.println("NO BOOKS FOUND");
        }
    }
    public static void main(String[] args) {
        displayAllBooks();
    }
}

Please write a Java program that displays detailed information about all the books in a library. Each book includes a title, author, ISBN number, and publication year. The program should read this information from a predefined list of books and display it in a formatted manner. Include separators before and after displaying each book's information. Additionally, if the book list is empty, an appropriate message should be printed.
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;
class Book {
    private String title;
    private String author;
    private String isbn;
    private int year;
    public Book(String title, String author, String isbn, int year) {
    }
    public String getTitle() {
    }
    public String getAuthor() {
    }
    public String getIsbn() {
    }
    public int getYear() {
    }
}
class BookReader {
    public static List<Book> getAll() {
    }
}
public class LibraryDisplay {
    private static final int WIDTH = 50;
    public static void displayAllBooks() {
    }
}
```

import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class BookTest {
    @Test
    void testBookConstructorAndGetters() {
        Book book = new Book("Java编程思想", "Bruce Eckel", "978-0131872486", 2006);
        assertEquals("Java编程思想", book.getTitle());
        assertEquals("Bruce Eckel", book.getAuthor());
        assertEquals("978-0131872486", book.getIsbn());
        assertEquals(2006, book.getYear());
    }
}
class BookReaderTest {
    @Test
    void testGetAllBooksCount() {
        List<Book> books = BookReader.getAll();
        assertNotNull(books);
        assertEquals(2, books.size());
    }
    @Test
    void testGetAllBooksContents() {
        List<Book> books = BookReader.getAll();
        Book book1 = books.get(0);
        Book book2 = books.get(1);
        assertEquals("Java编程思想", book1.getTitle());
        assertEquals("Bruce Eckel", book1.getAuthor());
        assertEquals("978-0131872486", book1.getIsbn());
        assertEquals(2006, book1.getYear());
        assertEquals("Effective Java", book2.getTitle());
        assertEquals("Joshua Bloch", book2.getAuthor());
        assertEquals("978-0134685991", book2.getIsbn());
        assertEquals(2018, book2.getYear());
    }
}
class LibraryDisplayTest {
    @Test
    void testDisplayAllBooks() {
        boolean booksDisplayedCorrectly = false;
        List<Book> books = BookReader.getAll();
        if (!books.isEmpty()) {
            booksDisplayedCorrectly = true;
            for (Book book : books) {
                assertNotNull(book.getTitle());
                assertNotNull(book.getAuthor());
                assertNotNull(book.getIsbn());
                assertTrue(book.getYear() > 0);
            }
        }
        assertTrue(booksDisplayedCorrectly);
    }
}


import java.util.Objects;
class PersonAssert {
    private Person actual;
    private static final String ERROR_MESSAGE = "\n期望的年龄为:\n  <%s>\n但实际的年龄为:\n  <%s>";
    public PersonAssert(Person actual) {
        this.actual = actual;
    }
    public PersonAssert isNotNull() {
        if (actual == null) {
            throw new AssertionError("Person对象不应该为null");
        }
        return this;
    }
    public PersonAssert assertAge(Integer expectedAge) {
        isNotNull();
        Integer actualAge = actual.getAge();
        if (!Objects.equals(actualAge, expectedAge)) {
            throw new AssertionError(String.format(ERROR_MESSAGE, expectedAge, actualAge));
        }
        return this;
    }
}
class Person {
    private Integer age;
    public Person(Integer age) {
        this.age = age;
    }
    public Integer getAge() {
        return age;
    }
}
public class Main {
    public static void main(String[] args) {
        check(25, true);
        check(30, false);
    }
    static void check(Integer ageToTest, boolean shouldPass) {
        Person person = new Person(25);
        PersonAssert personAssert = new PersonAssert(person);
        try {
            personAssert.assertAge(ageToTest);
            if (!shouldPass) {
                System.out.println("应该抛出异常，因为实际年龄与期望年龄不符");
            } else {
                System.out.println("断言成功，年龄匹配");
            }
        } catch (AssertionError error) {
            if (shouldPass) {
                System.out.println("不应该抛出异常，因为实际年龄与期望年龄相符");
            } else {
                System.out.println("断言失败，抛出异常，这是预期的");
            }
        }
    }
}

Please design a Java class `PersonAssert` that asserts the age attribute of a `Person` object. If the assertion fails, it should throw an exception showing the expected age and the actual age. Please implement the `assertAge` method according to the following requirements:

- The method should verify if the age of the `Person` object is equal to the given age.
- If they are not equal, it should throw an exception providing detailed error information.
- The method should support method chaining, i.e., return the current `PersonAssert` object so that other assertion methods can be called in succession.

Please provide a `Person` class containing only an `age` attribute and a corresponding `getAge` method.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Objects;
class PersonAssert {
    private Person actual;
    private static final String ERROR_MESSAGE = "\n期望的年龄为:\n  <%s>\n但实际的年龄为:\n  <%s>";
    public PersonAssert(Person actual) {
    }
    public PersonAssert isNotNull() {
        return this;
    }
    public PersonAssert assertAge(Integer expectedAge) {
        return this;
    }
}
class Person {
    private Integer age;
    public Person(Integer age) {
    }
    public Integer getAge() {
        return null;
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PersonAssertTest {
    @Test
    void testIsNotNullWithNonNullPerson() {
        Person person = new Person(25);
        PersonAssert personAssert = new PersonAssert(person);
        assertDoesNotThrow(personAssert::isNotNull);
    }
    @Test
    void testIsNotNullWithNullPerson() {
        Person person = null;
        PersonAssert personAssert = new PersonAssert(person);
        AssertionError thrown = assertThrows(AssertionError.class, personAssert::isNotNull);
        assertEquals("Person对象不应该为null", thrown.getMessage());
    }
    @Test
    void testAssertAgeWithMatchingAge() {
        Person person = new Person(25);
        PersonAssert personAssert = new PersonAssert(person);
        assertDoesNotThrow(() -> personAssert.assertAge(25));
    }
    @Test
    void testAssertAgeWithNonMatchingAge() {
        Person person = new Person(25);
        PersonAssert personAssert = new PersonAssert(person);
        AssertionError thrown = assertThrows(AssertionError.class, () -> personAssert.assertAge(30));
        assertEquals("\n期望的年龄为:\n  <30>\n但实际的年龄为:\n  <25>", thrown.getMessage());
    }
    @Test
    void testAssertAgeWithNullAge() {
        Person person = new Person(null);
        PersonAssert personAssert = new PersonAssert(person);
        AssertionError thrown = assertThrows(AssertionError.class, () -> personAssert.assertAge(25));
        assertEquals("\n期望的年龄为:\n  <25>\n但实际的年龄为:\n  <null>", thrown.getMessage());
    }
}


import java.util.List;
import java.util.Arrays;
public class UrlRedirectService {
    public String redirectToHomePage(List<String> roles) {
        if (roles.contains("ADMIN")) {
            return "/dashboard";
        } else if (roles.contains("USER")) {
            return "/homepage";
        } else {
            return "/login";
        }
    }
    public static void main(String[] args) {
        UrlRedirectService service = new UrlRedirectService();
        assert "/dashboard".equals(service.redirectToHomePage(Arrays.asList("ADMIN")));
        assert "/homepage".equals(service.redirectToHomePage(Arrays.asList("USER")));
        assert "/login".equals(service.redirectToHomePage(Arrays.asList("GUEST")));
        System.out.println("所有测试用例都通过了!");
    }
}

Please complete a Java programming task to implement a URL redirection service class that returns different page paths based on a user's roles.

**Task Requirements:**

Implement a Java class named `UrlRedirectService` that includes the following method:

- **Method Signature**: `public String redirectToHomePage(List<String> roles)`
- **Parameter Explanation**: The method takes a list of strings, `roles`, which represents the user's roles.
- **Return Value**: Based on the list of roles, return the corresponding page path:
  - If the role list contains `"ADMIN"`, return `"/dashboard"`.
  - If the role list contains `"USER"` (but does not contain `"ADMIN"`), return `"/homepage"`.
  - If the role list contains neither `"ADMIN"` nor `"USER"`, return `"/login"`.

Please implement the complete code in Java without a `Main` function, adhering to the following type definition:

```java
import java.util.List;
import java.util.Arrays;

public class UrlRedirectService {
    public String redirectToHomePage(List<String> roles) { }
}
```

import java.util.List;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
public class UrlRedirectServiceTest {
    @Test
    public void testRedirectToHomePage_AdminRole() {
        UrlRedirectService service = new UrlRedirectService();
        List<String> roles = Arrays.asList("ADMIN");
        String result = service.redirectToHomePage(roles);
        assertEquals("/dashboard", result);
    }
    @Test
    public void testRedirectToHomePage_UserRole() {
        UrlRedirectService service = new UrlRedirectService();
        List<String> roles = Arrays.asList("USER");
        String result = service.redirectToHomePage(roles);
        assertEquals("/homepage", result);
    }
    @Test
    public void testRedirectToHomePage_GuestRole() {
        UrlRedirectService service = new UrlRedirectService();
        List<String> roles = Arrays.asList("GUEST");
        String result = service.redirectToHomePage(roles);
        assertEquals("/login", result);
    }
    @Test
    public void testRedirectToHomePage_EmptyRoles() {
        UrlRedirectService service = new UrlRedirectService();
        List<String> roles = Arrays.asList();
        String result = service.redirectToHomePage(roles);
        assertEquals("/login", result);
    }
    @Test
    public void testRedirectToHomePage_MultipleRoles() {
        UrlRedirectService service = new UrlRedirectService();
        List<String> roles = Arrays.asList("USER", "ADMIN");
        String result = service.redirectToHomePage(roles);
        assertEquals("/dashboard", result);
    }
}


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class InventoryManager {
    public boolean removeProductAsync(String productName) throws ExecutionException, InterruptedException {
        CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
            if ("电视机".equals(productName)) {
                return true;
            } else {
                return false;
            }
        });
        boolean removed = future.get();
        return removed;
    }
    public static void main(String[] args) {
        InventoryManager manager = new InventoryManager();
        try {
            boolean isRemoved = manager.removeProductAsync("电视机");
            System.out.println("商品移除状态: " + (isRemoved ? "已移除" : "未找到"));
            isRemoved = manager.removeProductAsync("冰箱");
            System.out.println("商品移除状态: " + (isRemoved ? "已移除" : "未找到"));
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Please write a Java method that asynchronously checks whether a product has been removed from the inventory of an online store. If the product is successfully removed, return `true`; if the product is not found, return `false`. Ensure that your code is self-contained and 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.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class InventoryManager {
    public boolean removeProductAsync(String productName) throws ExecutionException, InterruptedException {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.ExecutionException;
public class InventoryManagerTest {
    @Test
    public void testRemoveProductAsyncWithExistingProduct() throws ExecutionException, InterruptedException {
        InventoryManager manager = new InventoryManager();
        boolean result = manager.removeProductAsync("电视机");
        assertTrue(result);
    }
    @Test
    public void testRemoveProductAsyncWithNonExistingProduct() throws ExecutionException, InterruptedException {
        InventoryManager manager = new InventoryManager();
        boolean result = manager.removeProductAsync("冰箱");
        assertFalse(result);
    }
    @Test
    public void testRemoveProductAsyncWithNullProduct() throws ExecutionException, InterruptedException {
        InventoryManager manager = new InventoryManager();
        boolean result = manager.removeProductAsync(null);
        assertFalse(result);
    }
    @Test
    public void testRemoveProductAsyncWithEmptyString() throws ExecutionException, InterruptedException {
        InventoryManager manager = new InventoryManager();
        boolean result = manager.removeProductAsync("");
        assertFalse(result);
    }
    @Test
    public void testRemoveProductAsyncWithDifferentProduct() throws ExecutionException, InterruptedException {
        InventoryManager manager = new InventoryManager();
        boolean result = manager.removeProductAsync("手机");
        assertFalse(result);
    }
}


import java.util.HashMap;
import java.util.Map;
class Student {
    private Map<Course, Integer> scores;
    public Student() {
        this.scores = new HashMap<>();
    }
    public void addScore(Course course, int score) {
        scores.put(course, score);
    }
    public int getScore(Course course) {
        return scores.getOrDefault(course, 0);
    }
}
class Course {
    private String name;
    public Course(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}
public class ExamChecker {
    static boolean isPassed(Student student, Course course) {
        return student.getScore(course) >= 60;
    }
    public static void main(String[] args) {
        Student student = new Student();
        Course math = new Course("数学");
        student.addScore(math, 75);
        boolean passed = isPassed(student, math);
        System.out.println("学生是否通过了数学考试？ " + passed);
    }
}

Please write a Java method to check whether a student has passed a specific course exam. The method accepts two parameters: a `Student` object and a `Course` object. If the student has passed the course exam, the method returns `true`; otherwise, it returns `false`. The condition for a student to pass the exam is: the student's score must be greater than or equal to 60 points.
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;
class Student {
    private Map<Course, Integer> scores;
    public Student() {
    }
    public void addScore(Course course, int score) {
    }
    public int getScore(Course course) {
    }
}
class Course {
    private String name;
    public Course(String name) {
    }
    public String getName() {
    }
}
public class ExamChecker {
    static boolean isPassed(Student student, Course course) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StudentTest {
    @Test
    void testAddScore() {
        Student student = new Student();
        Course math = new Course("数学");
        student.addScore(math, 75);
        assertEquals(75, student.getScore(math));
    }
    @Test
    void testGetScoreWithoutAdding() {
        Student student = new Student();
        Course science = new Course("科学");
        assertEquals(0, student.getScore(science));
    }
    @Test
    void testGetScoreWithDifferentSubject() {
        Student student = new Student();
        Course english = new Course("英语");
        Course history = new Course("历史");
        student.addScore(english, 85);
        assertEquals(0, student.getScore(history));
    }
    @Test
    void testIsPassed() {
        Student student = new Student();
        Course math = new Course("数学");
        student.addScore(math, 75);
        assertTrue(ExamChecker.isPassed(student, math));
    }
    @Test
    void testIsNotPassed() {
        Student student = new Student();
        Course physics = new Course("物理");
        student.addScore(physics, 55);
        assertFalse(ExamChecker.isPassed(student, physics));
    }
}


import java.lang.UnsupportedOperationException;
public class Reservation {
    private int bookingId;
    public Reservation(int bookingId) {
        this.bookingId = bookingId;
    }
    public int retrieveBookingId() {
        return this.bookingId;
    }
    public boolean checkBookingId(int expected) {
        return this.retrieveBookingId() == expected;
    }
    public static void main(String[] args) {
        Reservation reservation1 = new Reservation(123);
        Reservation reservation2 = new Reservation(456);
        System.out.println("Reservation 1 has booking ID 123: " + reservation1.checkBookingId(123));
        System.out.println("Reservation 2 has booking ID 456: " + reservation2.checkBookingId(456));
    }
}

Please write a Java class called `Reservation` that includes a method named `retrieveBookingId`. This method should return the value of a private member variable named `bookingId`. Ensure that this private member variable is correctly declared and initialized within the class, and provide a constructor to set its value. Additionally, write a method named `checkBookingId` to verify the correctness of the `retrieveBookingId` method.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.UnsupportedOperationException;
public class Reservation {
    private int bookingId;
    public Reservation(int bookingId) {
    }
    public int retrieveBookingId() {
    }
    public boolean checkBookingId(int expected) {
    }
}
```

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ReservationTest {
    @Test
    public void testRetrieveBookingId() {
        Reservation reservation = new Reservation(123);
        Assertions.assertEquals(123, reservation.retrieveBookingId());
    }
    @Test
    public void testCheckBookingIdTrue() {
        Reservation reservation = new Reservation(123);
        Assertions.assertTrue(reservation.checkBookingId(123));
    }
    @Test
    public void testCheckBookingIdFalse() {
        Reservation reservation = new Reservation(123);
        Assertions.assertFalse(reservation.checkBookingId(456));
    }
    @Test
    public void testRetrieveBookingIdDifferentInstance() {
        Reservation reservation = new Reservation(456);
        Assertions.assertEquals(456, reservation.retrieveBookingId());
    }
    @Test
    public void testCheckBookingIdDifferentInstanceFalse() {
        Reservation reservation = new Reservation(456);
        Assertions.assertFalse(reservation.checkBookingId(123));
    }
}


import java.util.ArrayList;
class Book {
    private String title;
    private String author;
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
    @Override
    public String toString() {
        return "书名: " + title + ", 作者: " + author;
    }
}
public class Library {
    public void displayBookList(ArrayList<Book> books) {
        System.out.println("\n图书馆藏书如下：");
        for (Book book : books) {
            System.out.println(book);
        }
    }
    public static void main(String[] args) {
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book("Java编程思想", "Bruce Eckel"));
        books.add(new Book("Effective Java", "Joshua Bloch"));
        books.add(new Book("深入理解Java虚拟机", "周志明"));
        Library library = new Library();
        library.displayBookList(books);
    }
}

Please write a Java program to display information about all books in a library. The book information includes the title and the author's name. It is required to implement this using an object-oriented approach, where the book information is represented using a separate class, and provide a method to print out all book information.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
class Book {
    private String title;
    private String author;
    public Book(String title, String author) {
    }
    @Override
    public String toString() {
    }
}
public class Library {
    public void displayBookList(ArrayList<Book> books) {
    }
}
```

import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class BookTest {
    @Test
    void testBookCreation() {
        Book book = new Book("Test Title", "Test Author");
        assertNotNull(book);
    }
    @Test
    void testBookToString() {
        Book book = new Book("Test Title", "Test Author");
        assertEquals("书名: Test Title, 作者: Test Author", book.toString());
    }
}
class LibraryTest {
    @Test
    void testDisplayBookListWithMultipleBooks() {
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book("Java编程思想", "Bruce Eckel"));
        books.add(new Book("Effective Java", "Joshua Bloch"));
        books.add(new Book("深入理解Java虚拟机", "周志明"));
        Library library = new Library();
        assertDoesNotThrow(() -> library.displayBookList(books));
    }
    @Test
    void testDisplayBookListWithEmptyList() {
        ArrayList<Book> books = new ArrayList<>();
        Library library = new Library();
        assertDoesNotThrow(() -> library.displayBookList(books));
    }
    @Test
    void testDisplayBookListWithOneBook() {
        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book("独自等待", "李傲"));
        Library library = new Library();
        assertDoesNotThrow(() -> library.displayBookList(books));
    }
}


import java.util.List;
public class BookManager {
    private List<String> bookList;
    public BookManager(List<String> bookList) {
        this.bookList = bookList;
    }
    public void updateBookList(List<String> newBookList) {
        this.bookList = newBookList;
        System.out.println("图书列表已更新。");
    }
    public List<String> getBookList() {
        return bookList;
    }
}
class BookManagerTest {
    public static void main(String[] args) {
        List<String> initialBooks = List.of("Java基础", "算法导论", "设计模式");
        BookManager manager = new BookManager(initialBooks);
        System.out.println("初始图书列表: " + manager.getBookList());
        List<String> updatedBooks = List.of("微服务架构", "Spring实战", "深入理解Java虚拟机");
        manager.updateBookList(updatedBooks);
        System.out.println("更新后的图书列表: " + manager.getBookList());
    }
}

Please write a Java description for a simple book management system design. Describe how the system would need a function to update the book list. When the book list changes, the system should be able to receive a list of strings containing book names and update the current book list.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.List;
public class BookManager {
    private List<String> bookList;
    public BookManager(List<String> bookList) {
    }
    public void updateBookList(List<String> newBookList) {
    }
    public List<String> getBookList() {
        return null;
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
public class BookManagerTest {
    private BookManager bookManager;
    private List<String> initialBooks;
    private List<String> updatedBooks;
    @BeforeEach
    public void setUp() {
        initialBooks = List.of("Java基础", "算法导论", "设计模式");
        bookManager = new BookManager(initialBooks);
        updatedBooks = List.of("微服务架构", "Spring实战", "深入理解Java虚拟机");
    }
    @Test
    public void testInitialBookList() {
        List<String> books = bookManager.getBookList();
        assertEquals(initialBooks, books, "Initial book list should match the list passed during instantiation.");
    }
    @Test
    public void testUpdateBookList() {
        bookManager.updateBookList(updatedBooks);
        List<String> books = bookManager.getBookList();
        assertEquals(updatedBooks, books, "Book list should be updated to the new list.");
    }
    @Test
    public void testEmptyBookList() {
        bookManager.updateBookList(List.of());
        List<String> books = bookManager.getBookList();
        assertTrue(books.isEmpty(), "Book list should be empty after updating with an empty list.");
    }
    @Test
    public void testNullBookList() {
        bookManager.updateBookList(null);
        List<String> books = bookManager.getBookList();
        assertNull(books, "Book list should be null after updating with a null list.");
    }
}


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileFinisher {
    public void writeAndCloseFile(String filePath, String data) throws IOException {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(filePath));
            writer.write(data);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
    public static void main(String[] args) {
        FileFinisher finisher = new FileFinisher();
        String testFilePath = "test.txt";
        String testData = "这是一个测试数据。";
        try {
            finisher.writeAndCloseFile(testFilePath, testData);
            System.out.println("文件写入和关闭操作成功。");
        } catch (IOException e) {
            System.err.println("发生错误：" + e.getMessage());
        }
    }
}

Please write a Java method that is used to perform a write operation to a text file and close the file after the write operation is completed. If an error occurs during writing or closing the file, an exception should be thrown.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileFinisher {
    public void writeAndCloseFile(String filePath, String data) throws IOException {
    }
}
```

import org.junit.jupiter.api.*;
import java.io.*;
public class FileFinisherTest {
    private FileFinisher fileFinisher;
    private final String testFilePath = "test.txt";
    @BeforeEach
    public void setUp() {
        fileFinisher = new FileFinisher();
    }
    @AfterEach
    public void tearDown() throws IOException {
        File file = new File(testFilePath);
        if (file.exists()) {
            file.delete();
        }
    }
    @Test
    public void testWriteAndCloseFileSuccess() throws IOException {
        String data = "This is test data.";
        fileFinisher.writeAndCloseFile(testFilePath, data);
        File file = new File(testFilePath);
        Assertions.assertTrue(file.exists());
        Assertions.assertEquals(data, readFileContent(testFilePath));
    }
    @Test
    public void testWriteAndCloseFileEmptyString() throws IOException {
        String data = "";
        fileFinisher.writeAndCloseFile(testFilePath, data);
        File file = new File(testFilePath);
        Assertions.assertTrue(file.exists());
        Assertions.assertEquals(data, readFileContent(testFilePath));
    }
    @Test
    public void testWriteAndCloseFileNonExistentDirectory() {
        String data = "This is test data.";
        String invalidFilePath = "nonexistent_directory/test.txt";
        Assertions.assertThrows(IOException.class, () -> {
            fileFinisher.writeAndCloseFile(invalidFilePath, data);
        });
    }
    private String readFileContent(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        }
        return content.toString();
    }
}