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

请编写一个Java方法，该方法能够查询并返回一个特定的图书信息。假设我们有一个图书管理系统，每本图书都有一个唯一的ID、书名和作者。现在我们需要根据图书的ID获取图书的详细信息。请实现一个名为`getBookDetails`的方法，该方法接收图书ID作为参数，并返回一个包含书名和作者的字符串。如果图书ID不存在，则返回一个指定的错误信息字符串。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java方法，用于获取指定任务所需的所有工具名称。假设我们有两种类型的任务：默认任务和自定义任务，每种任务都需要一组特定的工具来完成。默认任务的工具需求在`DefaultTask`类的`DEFAULT_TOOLS`常量中定义，而自定义任务的工具需求在`CustomTask`类的`CUSTOM_TOOLS`常量中定义。方法应该接受一个任务名称作为输入参数，并返回一个包含该任务及其所有依赖工具名称的集合。如果给定的任务名称既不是默认任务也不是自定义任务，则应抛出`IllegalArgumentException`。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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

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

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

 max_square = 0
 i = 2

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

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

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

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


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

请编写一个Java程序，实现一个简单的计算器类`SimpleCalculator`。这个类应该能够执行基本的算术运算：加法、减法、乘法和除法。请确保你的程序能够处理除以零的情况，抛出一个`ArithmeticException`异常，并附带错误信息"不能除以零"。请遵循以下指导原则：

- 代码必须包含所有必要的导入语句。
- 类和方法的命名应该清晰、简洁。
- 使用注释和文档字符串来增强代码的可读性。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Scanner;
public class SimpleCalculator {
    public double add(double a, double b) {

    }
    public double subtract(double a, double b) {

    }
    public double multiply(double a, double b) {

    }
    public double divide(double a, double b) throws ArithmeticException {

    }
}
```

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


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

请编写一个Java方法`convertToChineseName`，该方法接收一个整数参数`directionCode`，并根据该参数返回相应的中文方向名称。具体要求如下：

- 如果`directionCode`为1，返回"上"。
- 如果`directionCode`为2，返回"下"。
- 如果`directionCode`为3，返回"左"。
- 如果`directionCode`为4，返回"右"。
- 如果`directionCode`不是1、2、3、4中的任何一个，抛出`IllegalArgumentException`异常，并提示"无效的方向代码"。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java方法，该方法用于将一组学生的成绩加载到一个图形用户界面（GUI）表格中。假设你已经有一个名为`StudentScoreTable`的表格，你需要将学生姓名和他们的分数填充到这个表格中。学生信息是通过一个学生对象列表提供的，每个学生对象包含学生的姓名和分数。请确保你的方法能够创建一个适当的表格模型，并将学生数据正确填充到表格中。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java程序，实现一个简单的图书管理系统。该系统应该能够让用户添加图书信息，并且能够根据图书的名称查询图书信息。每本图书的信息包括图书的名称和作者。请确保你的代码是自包含的，并且所有使用到的包都在代码片段的开始部分被导入。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请设计一个简单的Java程序，用于管理一个图书馆的书籍借阅状态。图书馆中的每本书都可以处于三种状态之一：可借阅（AVAILABLE）、已借出（BORROWED）、或维修中（UNDER_REPAIR）。你需要实现一个名为`BookManager`的类，其中包含一个名为`updateBookStatus`的方法。该方法接收两个参数：`bookId`（书籍的唯一标识符）和`newStatus`（书籍的新状态），并根据这些信息更新书籍的状态。

请确保在设计中考虑所有必要的包。此外，提供一个`checkStatus`方法来返回书籍当前的状态。`checkStatus`方法应该接收一个书籍的标识符，并返回该书籍当前的状态。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java程序，用于计算银行账户的利息。程序应包含一个名为`BankAccount`的类，该类中包含一个名为`calculateInterest`的方法。该方法接收两个参数：`amount`（本金金额）和`duration`（存款期限，以年为单位），并返回计算得到的利息值。假设年利率为5%。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java方法，用于更新用户界面组件的鼠标光标样式。如果传入的光标对象是`null`，则应将组件的光标设置为默认光标。否则，应将组件的光标设置为传入的光标样式。请确保代码能够处理类型转换，并且在设置光标时不会引发异常。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java方法，用于生成一个简单的报告，该报告显示了一个虚拟图书馆中不同类型书籍的数量。报告应该以文本形式返回，格式为"类型: 数量"，每种类型一行。书籍的类型和数量通过一个`Map<String, Integer>`参数传入，其中键是书籍的类型，值是对应类型的书籍数量。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java程序，实现一个简单的购物车功能。在这个购物车中，用户可以添加商品名称到购物车列表中，也可以从列表中删除指定的商品名称。如果购物车变为空，则需要将其设置为null，表示购物车是空的。请确保你的代码是自包含的，并且包含了所有必要的包导入语句。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请设计一个Java程序，用于处理在线购物订单的取消操作。在一个电商平台上，当用户决定取消订单时，系统需要执行一系列的操作来更新订单状态，并且记录取消的时间戳。请实现一个名为`OrderCancellation`的类，其中包含一个名为`cancelOrder`的方法。该方法接收一个订单对象`Order`作为参数，并返回更新后的订单对象。如果订单已经被取消，则不执行任何操作直接返回原订单对象。订单取消后，需要将订单状态更新为"CANCELLED"，并记录取消的时间戳。

请遵循以下指导原则：
- 方法应该处理订单已经被取消的情况，即如果订单状态已经是"CANCELLED"，则直接返回订单对象不做任何修改。
- 订单取消后，需要更新订单状态为"CANCELLED"，并记录取消的时间戳。
- 使用`System.currentTimeMillis()`获取当前时间戳。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请设计一个简单的Java程序，用于模拟一个简易的天气系统。在这个系统中，我们需要能够根据不同的城市名称，返回该城市当前的天气状况。为了简化问题，我们假设只有三个城市：北京、上海和广州，它们的天气状况分别是晴天、多云和雨天。请实现一个名为`WeatherSystem`的类，其中包含一个名为`getWeather`的方法，该方法接受一个字符串参数（城市名称），并返回对应城市的天气状况。如果输入的城市不在我们的列表中，请返回一个提示信息，告知用户城市名称无效。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java程序，实现一个`TaskManager`类，该类中包含一个方法`boostTaskPriority`，用于提高任务的优先级。方法接收一个`double`类型的参数`priorityBoost`，表示需要增加的优先级数值。如果提升后的优先级超过了最大值10，则将优先级设置为10。此外，该类还应包含一个`getPriority`方法，用于获取当前任务的优先级。

请按照以下要求完成编程任务：

- 使用合适的访问修饰符确保封装性。
- 初始化时，任务的默认优先级为5。
- 提供一个检查方法`checkPriorityBoost`，用于验证`boostTaskPriority`方法的正确性。该方法应该打印出提升前后的优先级。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java方法，用于验证一个电子邮件对象是否包含特定的主题。如果电子邮件的主题与给定的主题不匹配，应抛出一个异常，异常信息需要明确指出预期的主题和实际的主题。请确保你的代码是自包含的，并且所有需要的包都已经导入。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请设计一个Java程序，用于管理一个简易的图书馆系统。在这个系统中，我们需要能够添加图书、删除图书和查找图书。每本图书包含书名和作者名。请实现以下功能：

1. 添加图书：当添加一本新书时，系统应该记录下这本书的书名和作者。
2. 删除图书：通过书名可以从系统中删除一本书。
3. 查找图书：通过书名可以查找一本书，并返回这本书的详细信息（书名和作者）。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.ArrayList;
import java.util.List;
public class SimpleLibrarySystem {
    private List<Book> books;
    public SimpleLibrarySystem() {
    }
    public void addBook(String title, String author) {
    }
    public void removeBook(String title) {
    }
    public Book findBook(String title) {
    }
    static class Book {
        String title;
        String author;
        public Book(String title, String author) {
        }
        @Override
        public String toString() {
        }
    }
}
```

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


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

请编写一个Java程序，用于验证用户输入的手机号码是否符合特定的格式要求。手机号码的格式要求如下：必须以"13", "14", "15", "17", 或 "18"开头，后面跟着9位数字。如果手机号码符合格式要求，则函数返回`true`；如果不符合，则抛出一个自定义的异常`InvalidPhoneNumberException`，异常信息为"无效的手机号码"。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请设计一个Java程序，实现一个简单的图书管理系统中的图书查询功能。用户可以通过输入图书的编号来查询图书的信息，包括图书的名称和作者。如果输入的编号不存在，则显示相应的错误消息。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java方法，该方法用于处理员工从一个部门转移到另一个部门的情况，并根据员工的新薪资和新部门预算情况来决定是否可以进行转移。如果新部门的预算足以支付员工的薪资，则转移可以进行，并且需要更新两个部门的预算情。如果预算不足，则转移不会发生。

请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java函数，该函数用于将一个学生的视图对象转换为模型对象。假设我们有一个学生追踪系统，其中`Student`类代表模型层，而`StudentView`类代表视图层。`Student`类包含学生的ID和姓名，而`StudentView`类则包含学生的视图信息，如姓名和邮箱。你需要完成一个名为`convertViewToModel`的函数，该函数接收一个`StudentView`对象作为参数，并返回一个`Student`对象。请注意，你需要从`StudentView`对象中获取学生的姓名，并将其设置到`Student`对象的相应属性中。确保所有必要的包都已经导入。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java方法，该方法接收一个Swing组件作为参数，并返回该组件在其父容器中的位置和大小。该方法应返回一个`Rectangle`对象，其中包含组件的x坐标、y坐标、宽度和高度。请确保你的方法能处理任何类型的Swing组件。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java方法，该方法用于将一本书添加到图书馆的收藏中。假设我们有两个实体：`Library`和`Book`。每个`Library`对象都有一个书籍列表，表示该图书馆收藏的书籍。书籍通过其唯一ID被添加到图书馆中。如果图书馆中已经有了这本书，则不会重复添加。请确保你的代码能够处理`Optional`类型，避免出现`NullPointerException`。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


import java.util.ArrayList;
public class ShoppingCart {
    private int selectedItemIndex = -1;
    public void selectItem(int index) {
        this.selectedItemIndex = index;
    }
    public int getSelectedItemIndex() {
        return selectedItemIndex;
    }
    public static void main(String[] args) {
        checkFunctionality();
    }
    public static void checkFunctionality() {
        ShoppingCart cart = new ShoppingCart();
        assert cart.getSelectedItemIndex() == -1 : "没有商品被选择时，应该返回-1。";
        cart.selectItem(2);
        assert cart.getSelectedItemIndex() == 2 : "选择了索引为2的商品，应该返回2。";
        cart.selectItem(5);
        assert cart.getSelectedItemIndex() == 5 : "更改选择到索引为5的商品，应该返回5。";
        System.out.println("所有测试通过！");
    }
}

请编写一个Java方法，用于处理购物车中商品的选择状态。当用户选择了一个商品后，该商品的位置（索引）会被记录下来。如果用户没有选择任何商品，索引值将会是-1。你需要实现一个方法，该方法返回当前选择的商品索引。如果没有商品被选择，返回-1。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.ArrayList;
public class ShoppingCart {
    private int selectedItemIndex = -1;
    public void selectItem(int index) {
    }
    public int getSelectedItemIndex() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class ShoppingCartTest {
    @Test
    public void testInitialSelectedItemIndex() {
        ShoppingCart cart = new ShoppingCart();
        assertEquals(-1, cart.getSelectedItemIndex());
    }
    @Test
    public void testSelectItem() {
        ShoppingCart cart = new ShoppingCart();
        cart.selectItem(2);
        assertEquals(2, cart.getSelectedItemIndex());
    }
    @Test
    public void testChangeSelectedItem() {
        ShoppingCart cart = new ShoppingCart();
        cart.selectItem(2);
        cart.selectItem(5);
        assertEquals(5, cart.getSelectedItemIndex());
    }
    @Test
    public void testSelectItemNegativeIndex() {
        ShoppingCart cart = new ShoppingCart();
        cart.selectItem(-3);
        assertEquals(-3, cart.getSelectedItemIndex());
    }
    @Test
    public void testSelectItemZeroIndex() {
        ShoppingCart cart = new ShoppingCart();
        cart.selectItem(0);
        assertEquals(0, cart.getSelectedItemIndex());
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class LineCounter {
    public static int countLines(String filePath) throws IOException {
        int lines = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            while (reader.readLine() != null) {
                lines++;
            }
        }
        return lines;
    }
    public static void main(String[] args) {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write("第一行文本\n第二行文本\n第三行文本");
            }
            int lineCount = countLines(tempFile.getAbsolutePath());
            System.out.println("文件中的行数为: " + lineCount);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
}

请编写一个Java程序，用于演示如何使用`BufferedReader`来逐行读取文本文件的内容。请确保你的程序能够处理异常，并且在读取文件之后正确地关闭资源。此外，你的程序应该能够计算并打印出文件中包含的行数。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
    public static int countLines(String filePath) throws IOException {
    }
}
```

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
import static org.junit.Assert.*;
public class LineCounterTest {
    @Test
    public void testCountLinesWithThreeLines() throws IOException {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write("第一行文本\n第二行文本\n第三行文本");
            }
            int lineCount = LineCounter.countLines(tempFile.getAbsolutePath());
            assertEquals(3, lineCount);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
    @Test
    public void testCountLinesWithEmptyFile() throws IOException {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            int lineCount = LineCounter.countLines(tempFile.getAbsolutePath());
            assertEquals(0, lineCount);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
    @Test
    public void testCountLinesWithOneLine() throws IOException {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write("只有一行文本");
            }
            int lineCount = LineCounter.countLines(tempFile.getAbsolutePath());
            assertEquals(1, lineCount);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
    @Test(expected = IOException.class)
    public void testCountLinesWithNonexistentFile() throws IOException {
        LineCounter.countLines("nonexistentFile.txt");
    }
    @Test
    public void testCountLinesWithMultipleNewLines() throws IOException {
        File tempFile = null;
        try {
            tempFile = File.createTempFile("testFile", ".txt");
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write("\n\n\n");
            }
            int lineCount = LineCounter.countLines(tempFile.getAbsolutePath());
            assertEquals(3, lineCount);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
}


import java.lang.IllegalArgumentException;
public class PermissionNotifier {
    public void notifyPermissionChange(int permissionCode, String appName) throws IllegalArgumentException {
        if (permissionCode < 0 || appName == null || appName.isEmpty()) {
            throw new IllegalArgumentException("非法的权限代码或应用名称");
        }
    }
    public static void main(String[] args) {
        PermissionNotifier notifier = new PermissionNotifier();
        try {
            notifier.notifyPermissionChange(100, "SampleApp");
            System.out.println("权限变更通知成功。");
        } catch (IllegalArgumentException e) {
            System.out.println("捕获到非法参数异常：" + e.getMessage());
        }
        try {
            notifier.notifyPermissionChange(-1, "InvalidApp");
        } catch (IllegalArgumentException e) {
            System.out.println("捕获到非法参数异常：" + e.getMessage());
        }
    }
}

请编写一个Java方法，该方法模拟了一个简化的权限变更通知系统。当一个应用的操作权限发生变化时需要通知相应的监听器。具体来说，你需要实现一个名为`PermissionNotifier`的类，其中包含一个名为`notifyPermissionChange`的方法。该方法接收两个参数：一个整数`permissionCode`代表权限代码，和一个字符串`appName`代表应用名称。如果权限代码或应用名称不合，方法应抛出一个`IllegalArgumentException`。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.lang.IllegalArgumentException;
public class PermissionNotifier {
    public void notifyPermissionChange(int permissionCode, String appName) throws IllegalArgumentException {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import java.lang.IllegalArgumentException;
public class PermissionNotifierTest {
    @Test
    public void testNotifyPermissionChange_ValidInputs() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertDoesNotThrow(() -> notifier.notifyPermissionChange(100, "ValidApp"));
    }
    @Test
    public void testNotifyPermissionChange_InvalidPermissionCode() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertThrows(IllegalArgumentException.class, () -> notifier.notifyPermissionChange(-1, "App"));
    }
    @Test
    public void testNotifyPermissionChange_NullAppName() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertThrows(IllegalArgumentException.class, () -> notifier.notifyPermissionChange(100, null));
    }
    @Test
    public void testNotifyPermissionChange_EmptyAppName() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertThrows(IllegalArgumentException.class, () -> notifier.notifyPermissionChange(100, ""));
    }
    @Test
    public void testNotifyPermissionChange_ZeroPermissionCode() {
        PermissionNotifier notifier = new PermissionNotifier();
        assertDoesNotThrow(() -> notifier.notifyPermissionChange(0, "AppWithZeroPermissionCode"));
    }
}


import java.util.Scanner;
public class SimpleCalculator {
    public void calculate(double num1, double num2, String operation) {
        switch (operation) {
            case "add":
                System.out.println("结果: " + (num1 + num2));
                break;
            case "subtract":
                System.out.println("结果: " + (num1 - num2));
                break;
            case "multiply":
                System.out.println("结果: " + (num1 * num2));
                break;
            case "divide":
                if (num2 == 0) {
                    System.out.println("错误: 除数不能为0");
                } else {
                    System.out.println("结果: " + (num1 / num2));
                }
                break;
            default:
                System.out.println("错误: 不支持的运算类型");
        }
    }
    public static void main(String[] args) {
        SimpleCalculator calculator = new SimpleCalculator();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一个数:");
        double num1 = scanner.nextDouble();
        System.out.println("请输入第二个数:");
        double num2 = scanner.nextDouble();
        scanner.nextLine();
        System.out.println("请输入运算类型（add, subtract, multiply, divide）:");
        String operation = scanner.nextLine();
        calculator.calculate(num1, num2, operation);
    }
}

请编写一个Java程序，实现一个简单的计算器功能。该计算器能够根据用户的输入执行加法、减法、乘法和除法运算。具体要求如下：

- 程序应包含一个名为`SimpleCalculator`的类。
- 类中应包含一个名为`calculate`的方法，该方法接受三个参数：两个`double`类型的数`num1`和`num2`，以及一个`String`类型的参数`operation`，表示要执行的运算类型（"add"、"subtract"、"multiply"、"divide"）。
- 根据`operation`的值，`calculate`方法应执行相应的运算，并打印出运算结果。
- 如果`operation`不是这四种运算之一，程序应打印出错误信息。
- 请确保在除法运算中，如果`num2`为0，则打印出错误信息，避免除以零的情况。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Scanner;
public class SimpleCalculator {
    public void calculate(double num1, double num2, String operation) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class SimpleCalculatorTest {
    @Test
    void testAddition() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 5.0;
        double num2 = 3.0;
        String operation = "add";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testSubtraction() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 5.0;
        double num2 = 3.0;
        String operation = "subtract";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testMultiplication() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 5.0;
        double num2 = 3.0;
        String operation = "multiply";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testDivision() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 6.0;
        double num2 = 3.0;
        String operation = "divide";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testDivisionByZero() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 6.0;
        double num2 = 0.0;
        String operation = "divide";
        calculator.calculate(num1, num2, operation);
    }
    @Test
    void testUnsupportedOperation() {
        SimpleCalculator calculator = new SimpleCalculator();
        double num1 = 6.0;
        double num2 = 3.0;
        String operation = "modulus";
        calculator.calculate(num1, num2, operation);
    }
}


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
public class StringCounter {
    public List<Map.Entry<String, Integer>> countAndSortStrings(List<Map.Entry<String, Integer>> entries) {
        HashMap<String, Integer> countMap = new HashMap<>();
        for (Map.Entry<String, Integer> entry : entries) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            countMap.put(key, countMap.getOrDefault(key, 0) + value);
        }
        List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(countMap.entrySet());
        Collections.sort(sortedList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        return sortedList;
    }
    public static void main(String[] args) {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("apple", 2));
        entries.add(new HashMap.SimpleEntry<>("banana", 3));
        entries.add(new HashMap.SimpleEntry<>("apple", 1));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        for (Map.Entry<String, Integer> entry : result) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

请编写一个Java程序，实现一个功能，该功能能够统计一组数据中每个唯一字符串出现的次数，并按照字符串的自然顺序输出结果。请确保你的程序能够处理一个包含字符串和对应次数的列表，并将统计结果以字符串和次数的形式输出。此外，输出的字符串应该按照自然顺序排序。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
public class StringCounter {
    public List<Map.Entry<String, Integer>> countAndSortStrings(List<Map.Entry<String, Integer>> entries) {
    }
}
```

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
import org.junit.Test;
import static org.junit.Assert.*;
public class StringCounterTest {
    @Test
    public void testCountAndSortStrings_singleEntry() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("apple", 2));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertEquals(1, result.size());
        assertEquals("apple", result.get(0).getKey());
        assertEquals(Integer.valueOf(2), result.get(0).getValue());
    }
    @Test
    public void testCountAndSortStrings_multipleEntriesSameKey() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("apple", 2));
        entries.add(new HashMap.SimpleEntry<>("apple", 1));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertEquals(1, result.size());
        assertEquals("apple", result.get(0).getKey());
        assertEquals(Integer.valueOf(3), result.get(0).getValue());
    }
    @Test
    public void testCountAndSortStrings_multipleEntriesDifferentKeys() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("banana", 3));
        entries.add(new HashMap.SimpleEntry<>("apple", 1));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertEquals(2, result.size());
        assertEquals("apple", result.get(0).getKey());
        assertEquals(Integer.valueOf(1), result.get(0).getValue());
        assertEquals("banana", result.get(1).getKey());
        assertEquals(Integer.valueOf(3), result.get(1).getValue());
    }
    @Test
    public void testCountAndSortStrings_emptyList() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertTrue(result.isEmpty());
    }
    @Test
    public void testCountAndSortStrings_mixedEntries() {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        entries.add(new HashMap.SimpleEntry<>("banana", 3));
        entries.add(new HashMap.SimpleEntry<>("apple", 1));
        entries.add(new HashMap.SimpleEntry<>("banana", 2));
        StringCounter counter = new StringCounter();
        List<Map.Entry<String, Integer>> result = counter.countAndSortStrings(entries);
        assertEquals(2, result.size());
        assertEquals("apple", result.get(0).getKey());
        assertEquals(Integer.valueOf(1), result.get(0).getValue());
        assertEquals("banana", result.get(1).getKey());
        assertEquals(Integer.valueOf(5), result.get(1).getValue());
    }
}