import java.util.HashMap;
import java.util.Map;
public class ColumnValueConverter {
    private Map<Integer, Object> columnData;
    public ColumnValueConverter() {
        columnData = new HashMap<>();
    }
    public void setColumnValue(int col, Object value) {
        columnData.put(col, value);
    }
    public int getIntegerFromColumn(int col) {
        Object value = columnData.get(col);
        if (value == null) {
            return 0;
        }
        if (value instanceof Boolean) {
            return (Boolean) value ? 1 : 0;
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            try {
                return (int) Double.parseDouble(value.toString());
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("无法将列值转换为整数。");
            }
        }
    }
    public static void main(String[] args) {
        ColumnValueConverter converter = new ColumnValueConverter();
        converter.setColumnValue(1, null);
        converter.setColumnValue(2, true);
        converter.setColumnValue(3, false);
        converter.setColumnValue(4, "123");
        converter.setColumnValue(5, "123.456");
        converter.setColumnValue(6, "非数字");
        assert converter.getIntegerFromColumn(1) == 0 : "列值为null时应返回0";
        assert converter.getIntegerFromColumn(2) == 1 : "列值为true时应返回1";
        assert converter.getIntegerFromColumn(3) == 0 : "列值为false时应返回0";
        assert converter.getIntegerFromColumn(4) == 123 : "列值为数字字符串时应转换为整数";
        assert converter.getIntegerFromColumn(5) == 123 : "列值为浮点数字符串时应转换为整数";
        try {
            converter.getIntegerFromColumn(6);
            assert false : "列值为非数字字符串时应抛出异常";
        } catch (IllegalArgumentException e) {
            assert true : "列值为非数字字符串时应抛出异常";
        }
        System.out.println("所有测试通过！");
    }
}

请编写一个Java方法，该方法接收一个表示列索引的整数参数，并返回该列的值转换为整数的结果。如果列值为null，返回0。如果列值是布尔类型，返回1（true）或0（false）。如果列值是其他类型，尝试将其转换为整数。如果无法直接转换，尝试将其转换为双精度浮点数，然后转换为整数。请确保代码能够处理可能出现的异常。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.HashMap;
import java.util.Map;
public class ColumnValueConverter {
    private Map<Integer, Object> columnData;
    public ColumnValueConverter() {
    }
    public void setColumnValue(int col, Object value) {
    }
    public int getIntegerFromColumn(int col) {
    }
}
```

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ColumnValueConverterTest {
    private ColumnValueConverter converter;
    @BeforeEach
    public void setUp() {
        converter = new ColumnValueConverter();
    }
    @Test
    public void testColumnValueIsNull() {
        converter.setColumnValue(1, null);
        Assertions.assertEquals(0, converter.getIntegerFromColumn(1), "列值为null时应返回0");
    }
    @Test
    public void testColumnValueIsTrue() {
        converter.setColumnValue(2, true);
        Assertions.assertEquals(1, converter.getIntegerFromColumn(2), "列值为true时应返回1");
    }
    @Test
    public void testColumnValueIsFalse() {
        converter.setColumnValue(3, false);
        Assertions.assertEquals(0, converter.getIntegerFromColumn(3), "列值为false时应返回0");
    }
    @Test
    public void testColumnValueIsIntegerString() {
        converter.setColumnValue(4, "123");
        Assertions.assertEquals(123, converter.getIntegerFromColumn(4), "列值为数字字符串时应转换为整数");
    }
    @Test
    public void testColumnValueIsDoubleString() {
        converter.setColumnValue(5, "123.456");
        Assertions.assertEquals(123, converter.getIntegerFromColumn(5), "列值为浮点数字符串时应转换为整数");
    }
    @Test
    public void testColumnValueIsNonNumericString() {
        converter.setColumnValue(6, "非数字");
        Assertions.assertThrows(IllegalArgumentException.class, () -> converter.getIntegerFromColumn(6), "列值为非数字字符串时应抛出异常");
    }
}


import java.lang.StringBuilder;
public class AdRequestGenerator {
    public static String generateAdRequestParams(String adUnitType, String adUnitID, int adUnitPrice) {
        StringBuilder params = new StringBuilder();
        params.append("packageName=yourPackageName");
        params.append("&deviceID=yourDeviceID");
        params.append("&googleAID=yourGoogleAID");
        params.append("&networkType=yourNetworkType");
        params.append("&adType=").append(adUnitType);
        params.append("&adID=").append(adUnitID);
        params.append("&priceLevel=").append(adUnitPrice);
        return params.toString();
    }
    public static void main(String[] args) {
        String adUnitType = "video";
        String adUnitID = "ad123";
        int adUnitPrice = 5;
        String requestParams = generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        System.out.println(requestParams);
    }
}

请编写一个Java方法，用于生成并返回一个特定格式的字符串。该字符串是基于传入的广告单元信息（包括广告单元类型、广告单元ID和广告单元价格）以及一些固定的参数。这个字符串主要用于网络请求的参数。请确保你的代码满足以下要求：

- 方法名为`generateAdRequestParams`。
- 方法接收三个参数：`adUnitType`（广告单元类型，类型为`String`）、`adUnitID`（广告单元ID，类型为`String`）、`adUnitPrice`（广告单元价格，类型为`int`）。
- 字符串格式如下：`"packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=adUnitType&adID=adUnitID&priceLevel=adUnitPrice"`。其中`yourPackageName`、`yourDeviceID`、`yourGoogleAID`、`yourNetworkType`是固定的字符串值，而`adUnitType`、`adUnitID`和`adUnitPrice`则是根据方法参数动态生成的。
- 使用`&`符号连接每个参数。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.lang.StringBuilder;
public class AdRequestGenerator {
    public static String generateAdRequestParams(String adUnitType, String adUnitID, int adUnitPrice) {
    }
}
```

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.*;
public class AdRequestGeneratorTest {
    @Test
    public void testGenerateAdRequestParams_ValidInput() {
        String adUnitType = "banner";
        String adUnitID = "123abc";
        int adUnitPrice = 10;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=banner&adID=123abc&priceLevel=10";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
    @Test
    public void testGenerateAdRequestParams_EmptyAdType() {
        String adUnitType = "";
        String adUnitID = "123abc";
        int adUnitPrice = 10;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=&adID=123abc&priceLevel=10";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
    @Test
    public void testGenerateAdRequestParams_EmptyAdID() {
        String adUnitType = "video";
        String adUnitID = "";
        int adUnitPrice = 5;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=video&adID=&priceLevel=5";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
    @Test
    public void testGenerateAdRequestParams_NegativePrice() {
        String adUnitType = "native";
        String adUnitID = "ad123";
        int adUnitPrice = -1;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=native&adID=ad123&priceLevel=-1";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
    @Test
    public void testGenerateAdRequestParams_ZeroPrice() {
        String adUnitType = "interstitial";
        String adUnitID = "ad456";
        int adUnitPrice = 0;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=interstitial&adID=ad456&priceLevel=0";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
}


import java.util.List;
import java.util.ArrayList;
public class StringListProcessor {
    public String getStringAtIndex(List<String> stringList, String indexStr) {
        try {
            int index = Integer.parseInt(indexStr);
            return stringList.get(index);
        } catch (NumberFormatException e) {
            return "错误：索引不是有效的数字。";
        } catch (IndexOutOfBoundsException e) {
            return "错误：索引超出范围。";
        }
    }
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        System.out.println(processor.getStringAtIndex(list, "1"));
        System.out.println(processor.getStringAtIndex(list, "5"));
        System.out.println(processor.getStringAtIndex(list, "abc"));
    }
}

请编写一个Java方法，该方法接收一个字符串列表和一个字符串索引，然后返回列表中对应索引的字符串。如果索引无效（例如，超出范围或不是数字），方法应该捕获异常并返回一个特定的错误消息。请确保你的代码能够优雅地处理这些潜在的异常情况。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.List;
import java.util.ArrayList;
public class StringListProcessor {
    public String getStringAtIndex(List<String> stringList, String indexStr) {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
import java.util.List;
import java.util.ArrayList;
public class StringListProcessorTest {
    @Test
    public void testGetStringAtIndex_validIndex() {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        assertEquals("Python", processor.getStringAtIndex(list, "1"));
    }
    @Test
    public void testGetStringAtIndex_indexOutOfBound() {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        assertEquals("错误：索引超出范围。", processor.getStringAtIndex(list, "5"));
    }
    @Test
    public void testGetStringAtIndex_invalidIndex() {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        assertEquals("错误：索引不是有效的数字。", processor.getStringAtIndex(list, "abc"));
    }
    @Test
    public void testGetStringAtIndex_zeroIndex() {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        assertEquals("Java", processor.getStringAtIndex(list, "0"));
    }
    @Test
    public void testGetStringAtIndex_emptyList() {
        List<String> list = new ArrayList<>();
        StringListProcessor processor = new StringListProcessor();
        assertEquals("错误：索引超出范围。", processor.getStringAtIndex(list, "0"));
    }
}


import java.util.ArrayList;
import java.util.List;
public class LibraryManager {
    private List<Book> books;
    public LibraryManager() {
        this.books = new ArrayList<>();
    }
    public String addBook(String title, String author) {
        for (Book book : books) {
            if (book.getTitle().equals(title) && book.getAuthor().equals(author)) {
                return "书籍已存在。";
            }
        }
        books.add(new Book(title, author));
        return "书籍添加成功。";
    }
    private static class Book {
        private String title;
        private String author;
        public Book(String title, String author) {
            this.title = title;
            this.author = author;
        }
        public String getTitle() {
            return title;
        }
        public String getAuthor() {
            return author;
        }
    }
    public static void main(String[] args) {
        LibraryManager libraryManager = new LibraryManager();
        System.out.println(libraryManager.addBook("Java编程思想", "Bruce Eckel"));
        System.out.println(libraryManager.addBook("Effective Java", "Joshua Bloch"));
        System.out.println(libraryManager.addBook("Java编程思想", "Bruce Eckel"));
    }
}

请设计一段描述，用于管理一个图书馆的书籍信息。每本书包含书名和作者名。你需要实现一个方法，该方法接受书名和作者名作为参数，如果这本书已经存在于图书馆中，则返回一个提示信息表示书籍已存在；如果不存在，则将书籍添加到图书馆中，并返回一个提示信息表示添加成功。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.ArrayList;
import java.util.List;
public class LibraryManager {
    private List<Book> books;
    public LibraryManager() {
    }
    public String addBook(String title, String author) {
    }
    private static class Book {
        private String title;
        private String author;
        public Book(String title, String author) {
        }
        public String getTitle() {
        }
        public String getAuthor() {
        }
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class LibraryManagerTest {
    @Test
    void testAddBookOnce() {
        LibraryManager libraryManager = new LibraryManager();
        String result = libraryManager.addBook("Java编程思想", "Bruce Eckel");
        assertEquals("书籍添加成功。", result);
    }
    @Test
    void testAddBookTwiceDifferent() {
        LibraryManager libraryManager = new LibraryManager();
        libraryManager.addBook("Java编程思想", "Bruce Eckel");
        String result = libraryManager.addBook("Effective Java", "Joshua Bloch");
        assertEquals("书籍添加成功。", result);
    }
    @Test
    void testAddDuplicateBook() {
        LibraryManager libraryManager = new LibraryManager();
        libraryManager.addBook("Java编程思想", "Bruce Eckel");
        String result = libraryManager.addBook("Java编程思想", "Bruce Eckel");
        assertEquals("书籍已存在。", result);
    }
    @Test
    void testAddBookWithDifferentAuthor() {
        LibraryManager libraryManager = new LibraryManager();
        libraryManager.addBook("Java编程思想", "Bruce Eckel");
        String result = libraryManager.addBook("Java编程思想", "Another Author");
        assertEquals("书籍添加成功。", result);
    }
    @Test
    void testAddBookWithoutTitle() {
        LibraryManager libraryManager = new LibraryManager();
        String result = libraryManager.addBook("", "Some Author");
        assertEquals("书籍添加成功。", result);
    }
}


public class StringEditor {
    private StringBuilder content;
    public StringEditor() {
        this.content = new StringBuilder();
    }
    public void addText(String text) {
        content.append(text);
    }
    public void replaceChar(int index, char newChar) {
        if (index >= 0 && index < content.length()) {
            content.setCharAt(index, newChar);
        }
    }
    public void deleteChar(int index) {
        if (index >= 0 && index < content.length()) {
            content.deleteCharAt(index);
        }
    }
    @Override
    public String toString() {
        return content.toString();
    }
    public static void main(String[] args) {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        System.out.println(editor);
        editor.replaceChar(1, 'a');
        System.out.println(editor);
        editor.deleteChar(4);
        System.out.println(editor);
    }
}

请编写一个Java程序，实现一个简单的文本编辑器功能，该编辑器能够进行文本的添加、替换和删除操作。具体要求如下：

1. 使用`StringEditor`类来实现这个文本编辑器。
2. 在`StringEditor`类中，使用`StringBuilder`来存储和操作文本字符串。
3. 实现`addText`方法，该方法接受一个字符串参数，并将其添加到当前文本的末尾。
4. 实现`replaceChar`方法，该方法接受两个参数：要替换的字符位置（从0开始计数）和新的字符，然后在指定位置替换字符。
5. 实现`deleteChar`方法，该方法接受一个参数：要删除的字符位置（从0开始计数），然后删除该位置的字符。

请注意，所有的操作都应该尽可能高效。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
public class StringEditor {
    private StringBuilder content;
    public StringEditor() {}
    public void addText(String text) {}
    public void replaceChar(int index, char newChar) {}
    public void deleteChar(int index) {}
    @Override
    public String toString() {}
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class StringEditorTest {
    @Test
    void testAddText() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        assertEquals("hello", editor.toString());
    }
    @Test
    void testReplaceChar() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        editor.replaceChar(1, 'a');
        assertEquals("hallo", editor.toString());
    }
    @Test
    void testReplaceCharOutOfBounds() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        editor.replaceChar(5, 'a');
        assertEquals("hello", editor.toString());
    }
    @Test
    void testDeleteChar() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        editor.deleteChar(4);
        assertEquals("hell", editor.toString());
    }
    @Test
    void testDeleteCharOutOfBounds() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        editor.deleteChar(5);
        assertEquals("hello", editor.toString());
    }
}


import java.util.Objects;
public class CsvUtil {
    public static String prepareForCsv(String input) {
        if (input == null) {
            return "";
        }
        String escapedInput = input.replace("\"", "\"\"");
        return "\"" + escapedInput + "\"";
    }
    public static void main(String[] args) {
        System.out.println(checkPrepareForCsv(null, ""));
        System.out.println(checkPrepareForCsv("", "\"\""));
        System.out.println(checkPrepareForCsv("Hello", "\"Hello\""));
        System.out.println(checkPrepareForCsv("Hello\"World", "\"Hello\"\"World\""));
    }
    private static boolean checkPrepareForCsv(String input, String expected) {
        return Objects.equals(prepareForCsv(input), expected);
    }
}

请编写一个Java方法，该方法用于处理字符串，使其适合CSV文件格式。具体来说，如果字符串中包含特殊字符（如双引号），则需要对这些字符进行转义。同时，无论字符串是否包含特殊字符，都需要在字符串的前后添加双引号。请遵循以下规则：

1. 如果输入字符串为null，返回一个空字符串。
2. 如果输入字符串为空，返回两个双引号（""）。
3. 如果输入字符串中包含双引号（"），则需要将每个双引号替换为两个双引号（""）。
4. 在处理完上述规则后，将整个字符串用一对双引号包裹。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Objects;
public class CsvUtil {
    public static String prepareForCsv(String input) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CsvUtilTest {
    @Test
    public void testPrepareForCsv_NullInput() {
        String result = CsvUtil.prepareForCsv(null);
        assertEquals("", result);
    }
    @Test
    public void testPrepareForCsv_EmptyString() {
        String result = CsvUtil.prepareForCsv("");
        assertEquals("\"\"", result);
    }
    @Test
    public void testPrepareForCsv_SimpleString() {
        String result = CsvUtil.prepareForCsv("Hello");
        assertEquals("\"Hello\"", result);
    }
    @Test
    public void testPrepareForCsv_StringWithQuote() {
        String result = CsvUtil.prepareForCsv("Hello\"World");
        assertEquals("\"Hello\"\"World\"", result);
    }
    @Test
    public void testPrepareForCsv_OnlyQuotes() {
        String result = CsvUtil.prepareForCsv("\"\"");
        assertEquals("\"\"\"\"\"\"", result);
    }
}


import java.util.Scanner;
public class SimpleCalculator {
    public static int calculate(int num1, int num2, char operator) {
        switch (operator) {
            case '+':
                return num1 + num2;
            case '-':
                return num1 - num2;
            case '*':
                return num1 * num2;
            case '/':
                if (num2 == 0) {
                    throw new IllegalArgumentException("除数不能为0");
                }
                return num1 / num2;
            default:
                throw new IllegalArgumentException("无效的运算符: " + operator);
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一个整数:");
        int num1 = scanner.nextInt();
        System.out.println("请输入第二个整数:");
        int num2 = scanner.nextInt();
        System.out.println("请输入运算符('+', '-', '*', '/'):");
        char operator = scanner.next().charAt(0);
        try {
            int result = calculate(num1, num2, operator);
            System.out.println("运算结果是: " + result);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

请编写一个Java程序，实现一个简单的计算器类`SimpleCalculator`。这个计算器需要包含一个方法`calculate`，该方法接收三个参数：两个整数`num1`和`num2`，以及一个字符`operator`。根据`operator`指定的运算符('+', '-', '*', '/')，对`num1`和`num2`进行相应的算术运算，并返回运算结果。如果`operator`是无效的运算符，方法应该抛出一个`IllegalArgumentException`。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Scanner;
public class SimpleCalculator {
    public static int calculate(int num1, int num2, char operator) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SimpleCalculatorTest {
    @Test
    public void testAddition() {
        int result = SimpleCalculator.calculate(3, 5, '+');
        assertEquals(8, result);
    }
    @Test
    public void testSubtraction() {
        int result = SimpleCalculator.calculate(10, 4, '-');
        assertEquals(6, result);
    }
    @Test
    public void testMultiplication() {
        int result = SimpleCalculator.calculate(6, 7, '*');
        assertEquals(42, result);
    }
    @Test
    public void testDivision() {
        int result = SimpleCalculator.calculate(20, 4, '/');
        assertEquals(5, result);
    }
    @Test
    public void testDivisionByZero() {
        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
            SimpleCalculator.calculate(10, 0, '/');
        });
        assertEquals("除数不能为0", exception.getMessage());
    }
    @Test
    public void testInvalidOperator() {
        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
            SimpleCalculator.calculate(10, 5, '%');
        });
        assertEquals("无效的运算符: %", exception.getMessage());
    }
}


import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class FileReaderUtil {
    public static String readUntilChar(String filePath, char[] stopChars) throws IOException {
        StringBuilder content = new StringBuilder();
        FileReader reader = null;
        try {
            reader = new FileReader(filePath);
            int c;
            while ((c = reader.read()) != -1) {
                if (Arrays.binarySearch(stopChars, (char) c) >= 0) {
                    break;
                }
                content.append((char) c);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return content.toString();
    }
    public static void checkFunction() {
        String testFilePath = "testFile.txt";
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        try {
            String result = readUntilChar(testFilePath, stopChars);
            System.out.println("读取的内容（直到遇到指定字符）: " + result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        checkFunction();
    }
}

请编写一个Java方法，该方法用于从一个文本文件中读取字符，直到遇到指定的字符之一为止。该方法应该返回一个字符串，包含从文件开始到遇到指定字符之一为止的所有字符。如果文件中不包含任何指定的字符，则返回文件的全部内容。

请遵循以下指导原则：
- 方法应该接受两个参数：一个是表示文件路径的字符串，另一个是包含指定停止字符的字符数组。
- 使用异常处理来处理可能的文件读取错误。
- 确保在结束读取后关闭文件。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class FileReaderUtil {
    public static String readUntilChar(String filePath, char[] stopChars) throws IOException {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.io.*;
public class FileReaderUtilTest {
    @Test
    public void testReadUntilCharStopCharFound() throws IOException {
        String content = "hello world";
        File tempFile = File.createTempFile("testFile", ".txt");
        tempFile.deleteOnExit();
        try (FileWriter writer = new FileWriter(tempFile)) {
            writer.write(content);
        }
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        String result = FileReaderUtil.readUntilChar(tempFile.getAbsolutePath(), stopChars);
        assertEquals("h", result);
    }
    @Test
    public void testReadUntilCharNoStopChar() throws IOException {
        String content = "bcdfg";
        File tempFile = File.createTempFile("testFile", ".txt");
        tempFile.deleteOnExit();
        try (FileWriter writer = new FileWriter(tempFile)) {
            writer.write(content);
        }
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        String result = FileReaderUtil.readUntilChar(tempFile.getAbsolutePath(), stopChars);
        assertEquals(content, result);
    }
    @Test
    public void testReadUntilCharEmptyFile() throws IOException {
        File tempFile = File.createTempFile("testFile", ".txt");
        tempFile.deleteOnExit();
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        String result = FileReaderUtil.readUntilChar(tempFile.getAbsolutePath(), stopChars);
        assertEquals("", result);
    }
    @Test
    public void testReadUntilCharImmediateStopChar() throws IOException {
        String content = "ahello world";
        File tempFile = File.createTempFile("testFile", ".txt");
        tempFile.deleteOnExit();
        try (FileWriter writer = new FileWriter(tempFile)) {
            writer.write(content);
        }
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        String result = FileReaderUtil.readUntilChar(tempFile.getAbsolutePath(), stopChars);
        assertEquals("", result);
    }
    @Test
    public void testReadUntilCharIOException() {
        String filePath = "nonexistentfile.txt";
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        assertThrows(IOException.class, () -> {
            FileReaderUtil.readUntilChar(filePath, stopChars);
        });
    }
}


import java.util.ArrayList;
import java.util.List;
public class BookSearchManager {
    private List<String> allBooks;
    private List<String> filteredBooks;
    public BookSearchManager() {
        allBooks = new ArrayList<>();
        allBooks.add("Java编程思想");
        allBooks.add("深入理解Java虚拟机");
        allBooks.add("Effective Java");
        allBooks.add("Python编程从入门到实践");
        allBooks.add("算法导论");
    }
    public List<String> searchBooks(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return allBooks;
        } else {
            filteredBooks = new ArrayList<>();
            for (String book : allBooks) {
                if (book.toLowerCase().contains(keyword.toLowerCase())) {
                    filteredBooks.add(book);
                }
            }
            return filteredBooks;
        }
    }
    public static void main(String[] args) {
        BookSearchManager manager = new BookSearchManager();
        System.out.println("搜索 'Java': " + manager.searchBooks("Java"));
        System.out.println("搜索空字符串: " + manager.searchBooks(""));
    }
}

请设计一个Java程序，用于管理一个图书馆的书籍搜索功能。当用户输入一个搜索关键字时，程序应该能够返回所有包含该关键字的书籍标题。如果用户没有输入任何内容（即输入为空字符串），则应返回所有书籍。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.ArrayList;
import java.util.List;
public class BookSearchManager {
    private List<String> allBooks;
    private List<String> filteredBooks;
    public BookSearchManager() {
    }
    public List<String> searchBooks(String keyword) {
    }
}
```

import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class BookSearchManagerTest {
    @Test
    public void testSearchBooksWithKeyword() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks("Java");
        Assert.assertEquals(3, result.size());
        Assert.assertTrue(result.contains("Java编程思想"));
        Assert.assertTrue(result.contains("深入理解Java虚拟机"));
        Assert.assertTrue(result.contains("Effective Java"));
    }
    @Test
    public void testSearchBooksWithEmptyString() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks("");
        Assert.assertEquals(5, result.size());
    }
    @Test
    public void testSearchBooksWithNull() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks(null);
        Assert.assertEquals(5, result.size());
    }
    @Test
    public void testSearchBooksWithNonExistingKeyword() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks("C++");
        Assert.assertTrue(result.isEmpty());
    }
    @Test
    public void testSearchBooksCaseInsensitiveKeyword() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks("java");
        Assert.assertEquals(3, result.size());
        Assert.assertTrue(result.contains("Java编程思想"));
        Assert.assertTrue(result.contains("深入理解Java虚拟机"));
        Assert.assertTrue(result.contains("Effective Java"));
    }
}


import java.util.Scanner;
public class TextEditor {
    private String fontSize = "12";
    public void changeFontSize() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("------------------------");
        System.out.print("请输入新的字体大小: ");
        String newFontSize = scanner.nextLine();
        if (newFontSize.equals(fontSize)) {
            System.out.println("------------------------");
            System.out.println("字体大小未改变。");
            System.out.println("========================");
        } else {
            fontSize = newFontSize;
            System.out.println("------------------------");
            System.out.println("字体大小已更新为: " + fontSize);
            System.out.println("========================");
        }
    }
    public static void main(String[] args) {
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
    }
}

请编写一个Java程序，实现一个简单的文本编辑器中字体大小设置的功能。用户可以通过输入来改变文本的字体大小。如果用户输入的字体大小与当前设置相同，则程序应通知用户没有变化发生。否则，应更新字体大小并通知用户字体大小已更改。请确保你的程序能够处理用户输入，并且在更改字体大小之前和之后都有清晰的提示信息。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Scanner;
public class TextEditor {
    private String fontSize = "12";
    public void changeFontSize() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class TextEditorTest {
    @Test
    public void testChangeFontSizeNoChange() {
        String simulatedInput = "12\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
    @Test
    public void testChangeFontSizeChange() {
        String simulatedInput = "14\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
    @Test
    public void testChangeFontSizeInvalidInput() {
        String simulatedInput = "abc\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
    @Test
    public void testChangeFontSizeEmptyInput() {
        String simulatedInput = "\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
    @Test
    public void testChangeFontSizeLargeInput() {
        String simulatedInput = "1000\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
}


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Book {
    private Date addedDate;
    public Book(Date addedDate) {
        this.addedDate = addedDate;
    }
    public Date getAddedDate() {
        return addedDate;
    }
}
public class Library {
    private List<Book> books = new ArrayList<>();
    public void addBook(Book book) {
        books.add(book);
    }
    public int countBooksAddedBetween(Date start, Date end) {
        int count = 0;
        for (Book book : books) {
            Date addedDate = book.getAddedDate();
            if (!addedDate.before(start) && !addedDate.after(end)) {
                count++;
            }
        }
        return count;
    }
    public static void main(String[] args) {
        Library library = new Library();
        library.addBook(new Book(new Date(122, 4, 15)));
        library.addBook(new Book(new Date(122, 5, 10)));
        library.addBook(new Book(new Date(122, 6, 20)));
        Date start = new Date(122, 4, 1);
        Date end = new Date(122, 5, 30);
        int count = library.countBooksAddedBetween(start, end);
        System.out.println("新增图书数量: " + count);
    }
}

请编写一个Java程序，用于统计一个在线图书馆在特定时间段内新增的图书数量。图书馆的每本图书都有一个入库日期，你需要根据这个日期来判断图书是否在给定的时间段内新增。请确保你的程序能够接受两个日期作为输入（开始日期和结束日期），并返回这段时间内新增图书的数量。注意，开始日期和结束日期是包含在内的，即如果图书的入库日期等于开始日期或结束日期，也应该被计算在内。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Book {
    private Date addedDate;
    public Book(Date addedDate) {
    }
    public Date getAddedDate() {
    }
}
public class Library {
    private List<Book> books = new ArrayList<>();
    public void addBook(Book book) {
    }
    public int countBooksAddedBetween(Date start, Date end) {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.Date;
public class LibraryTest {
    @Test
    public void testAddBook() {
        Library library = new Library();
        library.addBook(new Book(new Date()));
        assertEquals(1, library.countBooksAddedBetween(new Date(Long.MIN_VALUE), new Date()));
    }
    @Test
    public void testCountBooksAddedBetween() {
        Library library = new Library();
        library.addBook(new Book(new Date(122, 4, 15)));
        library.addBook(new Book(new Date(122, 5, 10)));
        library.addBook(new Book(new Date(122, 6, 20)));
        Date start = new Date(122, 4, 1);
        Date end = new Date(122, 5, 30);
        int count = library.countBooksAddedBetween(start, end);
        assertEquals(2, count);
    }
    @Test
    public void testCountBooksAddedBetweenNoBooks() {
        Library library = new Library();
        Date start = new Date(122, 4, 1);
        Date end = new Date(122, 5, 30);
        int count = library.countBooksAddedBetween(start, end);
        assertEquals(0, count);
    }
    @Test
    public void testCountBooksAddedBetweenAllBooks() {
        Library library = new Library();
        library.addBook(new Book(new Date(122, 4, 15)));
        library.addBook(new Book(new Date(122, 5, 10)));
        library.addBook(new Book(new Date(122, 6, 20)));
        Date start = new Date(122, 4, 1);
        Date end = new Date(122, 6, 30);
        int count = library.countBooksAddedBetween(start, end);
        assertEquals(3, count);
    }
    @Test
    public void testCountBooksAddedBetweenEdgeCases() {
        Library library = new Library();
        library.addBook(new Book(new Date(122, 4, 15)));
        library.addBook(new Book(new Date(122, 5, 10)));
        library.addBook(new Book(new Date(122, 6, 20)));
        Date start = new Date(122, 5, 10);
        Date end = new Date(122, 6, 20);
        int count = library.countBooksAddedBetween(start, end);
        assertEquals(2, count);
    }
}


import java.util.Arrays;
import java.util.List;
public class FileUtil {
    public static boolean isImageType(String fileName) {
        List<String> supportedTypes = Arrays.asList(".jpg", ".png", ".gif", ".bmp");
        String extension = "";
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i).toLowerCase();
        }
        return supportedTypes.contains(extension);
    }
    public static void check() {
        System.out.println(isImageType("photo.jpg") == true ? "正确" : "错误");
        System.out.println(isImageType("document.pdf") == false ? "正确" : "错误");
        System.out.println(isImageType("image.png") == true ? "正确" : "错误");
        System.out.println(isImageType("animation.gif") == true ? "正确" : "错误");
        System.out.println(isImageType("archive.rar") == false ? "正确" : "错误");
    }
    public static void main(String[] args) {
        check();
    }
}

请编写一个Java方法，用于检查给定的文件扩展名是否表示一个图像文件。支持的图像文件类型包括`.jpg`, `.png`, `.gif`, 和 `.bmp`。如果文件扩展名匹配这些类型之一，则方法应返回`true`，否则返回`false`。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Arrays;
import java.util.List;
public class FileUtil {
    public static boolean isImageType(String fileName) {
    }
    public static void check() {
    }
}
```

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FileUtilTest {
    @Test
    public void testIsImageType_WithJpgExtension_ShouldReturnTrue() {
        assertTrue(FileUtil.isImageType("photo.jpg"));
    }
    @Test
    public void testIsImageType_WithPngExtension_ShouldReturnTrue() {
        assertTrue(FileUtil.isImageType("image.png"));
    }
    @Test
    public void testIsImageType_WithGifExtension_ShouldReturnTrue() {
        assertTrue(FileUtil.isImageType("animation.gif"));
    }
    @Test
    public void testIsImageType_WithPdfExtension_ShouldReturnFalse() {
        assertFalse(FileUtil.isImageType("document.pdf"));
    }
    @Test
    public void testIsImageType_WithRarExtension_ShouldReturnFalse() {
        assertFalse(FileUtil.isImageType("archive.rar"));
    }
}


import java.util.Calendar;
import java.util.TimeZone;
public class DateManager {
    public static long[] resetTimeMarkers() {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long todayStart = calendar.getTimeInMillis();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        long yesterdayStart = calendar.getTimeInMillis();
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        long yearStart = calendar.getTimeInMillis();
        return new long[]{todayStart, yesterdayStart, yearStart};
    }
    public static void checkTimeMarkers(long[] timeMarkers) {
        Calendar calendar = Calendar.getInstance();
        for (long timeMarker : timeMarkers) {
            calendar.setTimeInMillis(timeMarker);
            System.out.println(calendar.getTime());
        }
    }
    public static void main(String[] args) {
        long[] timeMarkers = resetTimeMarkers();
        checkTimeMarkers(timeMarkers);
    }
}

请编写一个Java程序，该程序包含一个名为`DateManager`的类，该类中有一个静态方法`resetTimeMarkers`。该方法用于计算并返回一个包含三个时间点的`long`类型数组：今天开始时刻、昨天开始时刻和今年开始时刻。这三个时间点都是以毫秒为单位的时间戳，分别代表当前年份的今天0点、昨天0点和1月1日0点。请确保返回的时间戳是准确的，并且考虑到时区的影响。

请按照以下要求实现代码：

1. 使用`java.util.Calendar`类来获取和设置时间。
2. 方法返回的数组中，第一个元素是今天开始时刻的时间戳，第二个元素是昨天开始时刻的时间戳，第三个元素是今年开始时刻的时间戳。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Calendar;
import java.util.TimeZone;
public class DateManager {
    public static long[] resetTimeMarkers() {
    }
    public static void checkTimeMarkers(long[] timeMarkers) {
    }
}
```

import org.junit.jupiter.api.Test;
import java.util.Calendar;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.*;
public class DateManagerTest {
    @Test
    public void testResetTimeMarkersTodayStart() {
        long[] timeMarkers = DateManager.resetTimeMarkers();
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        assertEquals(calendar.getTimeInMillis(), timeMarkers[0]);
    }
    @Test
    public void testResetTimeMarkersYesterdayStart() {
        long[] timeMarkers = DateManager.resetTimeMarkers();
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        assertEquals(calendar.getTimeInMillis(), timeMarkers[1]);
    }
    @Test
    public void testResetTimeMarkersYearStart() {
        long[] timeMarkers = DateManager.resetTimeMarkers();
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        assertEquals(calendar.getTimeInMillis(), timeMarkers[2]);
    }
    @Test
    public void testCheckTimeMarkers() {
        long[] timeMarkers = DateManager.resetTimeMarkers();
        Calendar calendar = Calendar.getInstance();
        for (long timeMarker : timeMarkers) {
            calendar.setTimeInMillis(timeMarker);
            assertNotNull(calendar.getTime());
        }
    }
}


import java.io.UnsupportedEncodingException;
public class StringEncoder {
    public String convertEncoding(String originalString, String desiredEncoding) throws UnsupportedEncodingException {
        byte[] bytes = originalString.getBytes(desiredEncoding);
        return new String(bytes, desiredEncoding);
    }
    public static void main(String[] args) {
        StringEncoder encoder = new StringEncoder();
        try {
            String originalString = "这是一个测试字符串";
            String desiredEncoding = "ISO-8859-1";
            String convertedString = encoder.convertEncoding(originalString, desiredEncoding);
            System.out.println("转换后的字符串: " + convertedString);
        } catch (UnsupportedEncodingException e) {
            System.err.println("不支持的编码格式: " + e.getMessage());
        }
    }
}

请编写一个Java程序，用于处理字符串中的特定编码转换。具体来说，你需要实现一个名为`StringEncoder`的类，该类中包含一个名为`convertEncoding`的方法。该方法接收两个字符串参数：第一个参数`originalString`代表原始字符串，第二个参数`desiredEncoding`代表希望转换到的编码格式（如"UTF-8"、"ISO-8859-1"等）。如果转换成功，方法应返回转换后的字符串；如果转换失败，应抛出一个`UnsupportedEncodingException`异常。

请确保实现满足以下要求：
- 必须导入必要的包。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.io.UnsupportedEncodingException;
public class StringEncoder {
    public String convertEncoding(String originalString, String desiredEncoding) throws UnsupportedEncodingException {
    }
}
```

import java.io.UnsupportedEncodingException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class StringEncoderTest {
    @Test
    public void testConvertEncoding_validEncoding() throws UnsupportedEncodingException {
        StringEncoder encoder = new StringEncoder();
        String originalString = "这是一个测试字符串";
        String desiredEncoding = "UTF-8";
        String encodedString = encoder.convertEncoding(originalString, desiredEncoding);
        assertNotNull(encodedString);
    }
    @Test
    public void testConvertEncoding_invalidEncoding() {
        StringEncoder encoder = new StringEncoder();
        String originalString = "这是一个测试字符串";
        String desiredEncoding = "INVALID_ENCODING";
        assertThrows(UnsupportedEncodingException.class, () -> {
            encoder.convertEncoding(originalString, desiredEncoding);
        });
    }
    @Test
    public void testConvertEncoding_emptyString() throws UnsupportedEncodingException {
        StringEncoder encoder = new StringEncoder();
        String originalString = "";
        String desiredEncoding = "UTF-8";
        String encodedString = encoder.convertEncoding(originalString, desiredEncoding);
        assertEquals("", encodedString);
    }
    @Test
    public void testConvertEncoding_differentEncodings() throws UnsupportedEncodingException {
        StringEncoder encoder = new StringEncoder();
        String originalString = "这是一个测试字符串";
        String utf8Encoded = encoder.convertEncoding(originalString, "UTF-8");
        String isoEncoded = encoder.convertEncoding(utf8Encoded, "ISO-8859-1");
        assertNotNull(isoEncoded);
    }
    @Test
    public void testConvertEncoding_nullString() {
        StringEncoder encoder = new StringEncoder();
        String desiredEncoding = "UTF-8";
        Exception exception = assertThrows(NullPointerException.class, () -> {
            encoder.convertEncoding(null, desiredEncoding);
        });
    }
}


import java.lang.UnsupportedOperationException;
public class ImageProcessor {
    public void initializePorts() {
        throw new UnsupportedOperationException("该方法尚未实现。");
    }
    public static void checkFunction() {
        ImageProcessor processor = new ImageProcessor();
        try {
            processor.initializePorts();
        } catch (UnsupportedOperationException e) {
            System.out.println("方法抛出了预期的异常：" + e.getMessage());
        }
    }
    public static void main(String[] args) {
        checkFunction();
    }
}

请编写一个Java方法，该方法用于在图像处理过滤器中设置输入和输出端口。该方法应该在一个名为`ImageProcessor`的类中，并且该类应该有一个名为`initializePorts`的公共方法。该方法不需要接受任何参数，并且应该抛出一个`UnsupportedOperationException`异常，表示该功能尚未实现。请确保包含所有必要的导入语句。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.lang.UnsupportedOperationException;
public class ImageProcessor {
    public void initializePorts() {
    }
}
```

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.UnsupportedOperationException;
public class ImageProcessorTest {
    @Test
    public void testInitializePortsThrowsException() {
        ImageProcessor processor = new ImageProcessor();
        Assertions.assertThrows(UnsupportedOperationException.class, processor::initializePorts);
    }
    @Test
    public void testInitializePortsThrowsExceptionWithMessage() {
        ImageProcessor processor = new ImageProcessor();
        UnsupportedOperationException exception = Assertions.assertThrows(UnsupportedOperationException.class, processor::initializePorts);
        Assertions.assertEquals("该方法尚未实现。", exception.getMessage());
    }
    @Test
    public void testCheckFunctionCatchesException() {
        try {
            ImageProcessor.checkFunction();
        } catch (Exception e) {
            Assertions.fail("checkFunction方法不应抛出任何异常，但抛出了: " + e);
        }
    }
    @Test
    public void testNewInstance() {
        ImageProcessor processor = new ImageProcessor();
        Assertions.assertNotNull(processor, "创建的ImageProcessor实例不应为null");
    }
}


import java.util.Locale;
interface Metric {}
interface Counting extends Metric {
    long getCount();
}
interface Gauge<T> extends Metric {
    T getValue();
}
interface Sampling extends Metric {
    double getSampleRate();
}
class Counter implements Counting {
    private long count;
    public Counter(long count) { this.count = count; }
    public long getCount() { return count; }
}
class GaugeDouble implements Gauge<Double> {
    private double value;
    public GaugeDouble(double value) { this.value = value; }
    public Double getValue() { return value; }
}
class Sample implements Sampling {
    private double sampleRate;
    public Sample(double sampleRate) { this.sampleRate = sampleRate; }
    public double getSampleRate() { return sampleRate; }
}
public class PerformanceSummary {
    public static void displayMetricInfo(StringBuilder sb, Metric[] metrics) {
        for (Metric metric : metrics) {
            if (metric instanceof Counting) {
                sb.append(String.format(Locale.US, "Count: %d\n", ((Counting) metric).getCount()));
            }
            if (metric instanceof Gauge) {
                sb.append(String.format(Locale.US, "Value: %.2f\n", ((Gauge<?>) metric).getValue()));
            }
            if (metric instanceof Sampling) {
                sb.append(String.format(Locale.US, "Sample Rate: %.2f%%\n", ((Sampling) metric).getSampleRate() * 100));
            }
        }
    }
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] {
            new Counter(150),
            new GaugeDouble(99.99),
            new Sample(0.85)
        };
        displayMetricInfo(sb, metrics);
        System.out.println(sb.toString());
    }
}

请编写一个Java程序，用于展示不同类型的性能指标信息。你需要定义一个名为`PerformanceSummary`的类，其中包含一个名为`displayMetricInfo`的方法。该方法接收一个`StringBuilder`对象和一个实现了`Metric`接口的对象数组。你需要根据不同的指标类型（计数、测量值、采样率）向`StringBuilder`中添加相应的信息。请确保程序能够处理不同类型的指标，并且格式整洁、易于阅读。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Locale;
interface Metric {}
interface Counting extends Metric {
    long getCount();
}
interface Gauge<T> extends Metric {
    T getValue();
}
interface Sampling extends Metric {
    double getSampleRate();
}
class Counter implements Counting {
    private long count;
    public Counter(long count) {}
    public long getCount() {}
}
class GaugeDouble implements Gauge<Double> {
    private double value;
    public GaugeDouble(double value) {}
    public Double getValue() {}
}
class Sample implements Sampling {
    private double sampleRate;
    public Sample(double sampleRate) {}
    public double getSampleRate() {}
}
public class PerformanceSummary {
    public static void displayMetricInfo(StringBuilder sb, Metric[] metrics) {}
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PerformanceSummaryTest {
    @Test
    public void testDisplayMetricInfo_withCounter() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] { new Counter(150) };
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("Count: 150\n", sb.toString());
    }
    @Test
    public void testDisplayMetricInfo_withGaugeDouble() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] { new GaugeDouble(99.99) };
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("Value: 99.99\n", sb.toString());
    }
    @Test
    public void testDisplayMetricInfo_withSample() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] { new Sample(0.85) };
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("Sample Rate: 85.00%\n", sb.toString());
    }
    @Test
    public void testDisplayMetricInfo_withMixedMetrics() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] {
            new Counter(150),
            new GaugeDouble(99.99),
            new Sample(0.85)
        };
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("Count: 150\nValue: 99.99\nSample Rate: 85.00%\n", sb.toString());
    }
    @Test
    public void testDisplayMetricInfo_withEmptyMetrics() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] {};
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("", sb.toString());
    }
}


import java.util.regex.Pattern;
public class PasswordStrengthValidator {
    public static boolean validatePasswordStrength(String password) {
        if (password.length() < 8) {
            return false;
        }
        if (!Pattern.compile("[a-z]").matcher(password).find()) {
            return false;
        }
        if (!Pattern.compile("[A-Z]").matcher(password).find()) {
            return false;
        }
        if (!Pattern.compile("[0-9]").matcher(password).find()) {
            return false;
        }
        if (!Pattern.compile("[^a-zA-Z0-9]").matcher(password).find()) {
            return false;
        }
        return true;
    }
    public static void main(String[] args) {
        checkPasswordStrength("WeakPass", false);
        checkPasswordStrength("StrongPass1!", true);
        checkPasswordStrength("NoSpecialChar1", false);
        checkPasswordStrength("Short1!", false);
        checkPasswordStrength("ValidPassword1@", true);
    }
    private static void checkPasswordStrength(String password, boolean expected) {
        boolean isValid = validatePasswordStrength(password);
        assert isValid == expected : "Password validation for \"" + password + "\" failed. Expected: " + expected + ", but got: " + isValid;
        System.out.println("Password \"" + password + "\" is " + (isValid ? "strong" : "weak") + ".");
    }
}

请编写一个Java程序，用于验证用户密码的强度。密码必须满足以下条件才被认为是有效的：
- 至少包含8个字符。
- 至少包含一个小写字母。
- 至少包含一个大写字母。
- 至少包含一个数字。
- 至少包含一个特殊字符（非字母数字字符）。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.regex.Pattern;
public class PasswordStrengthValidator {
    public static boolean validatePasswordStrength(String password) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class PasswordStrengthValidatorTest {
    @Test
    public void testShortPassword() {
        assertEquals(false, PasswordStrengthValidator.validatePasswordStrength("Short1!"));
    }
    @Test
    public void testNoSpecialCharacterPassword() {
        assertEquals(false, PasswordStrengthValidator.validatePasswordStrength("NoSpecialChar1"));
    }
    @Test
    public void testWeakPassword() {
        assertEquals(false, PasswordStrengthValidator.validatePasswordStrength("WeakPass"));
    }
    @Test
    public void testStrongPassword() {
        assertEquals(true, PasswordStrengthValidator.validatePasswordStrength("StrongPass1!"));
    }
    @Test
    public void testValidPasswordWithSpecialCharacter() {
        assertEquals(true, PasswordStrengthValidator.validatePasswordStrength("ValidPassword1@"));
    }
}


import java.util.HashMap;
import java.util.Map;
public class ErrorInfoProvider {
    public static String getErrorMessage(int errorCode) {
        Map<Integer, String> errorMap = new HashMap<>();
        errorMap.put(1, "网络连接失败");
        errorMap.put(2, "用户认证失败");
        errorMap.put(3, "数据格式错误");
        errorMap.put(4, "权限不足");
        errorMap.put(5, "服务器内部错误");
        errorMap.put(6, "数据更新失败");
        errorMap.put(7, "资源未找到");
        return errorMap.getOrDefault(errorCode, "未知错误");
    }
    public static void check() {
        assert "网络连接失败".equals(getErrorMessage(1));
        assert "用户认证失败".equals(getErrorMessage(2));
        assert "数据格式错误".equals(getErrorMessage(3));
        assert "权限不足".equals(getErrorMessage(4));
        assert "服务器内部错误".equals(getErrorMessage(5));
        assert "数据更新失败".equals(getErrorMessage(6));
        assert "资源未找到".equals(getErrorMessage(7));
        assert "未知错误".equals(getErrorMessage(8));
    }
    public static void main(String[] args) {
        check();
    }
}

请设计一个Java方法，该方法接收一个整型参数`errorCode`，根据不同的错误代码返回相应的错误信息。错误代码和对应的错误信息如下：

- 1: "网络连接失败"
- 2: "用户认证失败"
- 3: "数据格式错误"
- 4: "权限不足"
- 5: "服务器内部错误"
- 6: "数据更新失败"
- 7: "资源未找到"

如果传入的错误代码不在上述列表中，请返回"未知错误"。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.HashMap;
import java.util.Map;
public class ErrorInfoProvider {
    public static String getErrorMessage(int errorCode) {
    }
    public static void check() {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ErrorInfoProviderTest {
    @Test
    public void testGetErrorMessageForKnownErrorCodes() {
        assertEquals("网络连接失败", ErrorInfoProvider.getErrorMessage(1));
        assertEquals("用户认证失败", ErrorInfoProvider.getErrorMessage(2));
        assertEquals("数据格式错误", ErrorInfoProvider.getErrorMessage(3));
        assertEquals("权限不足", ErrorInfoProvider.getErrorMessage(4));
        assertEquals("服务器内部错误", ErrorInfoProvider.getErrorMessage(5));
    }
    @Test
    public void testGetErrorMessageForUnknownErrorCode() {
        assertEquals("未知错误", ErrorInfoProvider.getErrorMessage(999));
    }
    @Test
    public void testGetErrorMessageForBoundaryErrorCode() {
        assertEquals("网络连接失败", ErrorInfoProvider.getErrorMessage(1));
        assertEquals("未知错误", ErrorInfoProvider.getErrorMessage(0));
    }
    @Test
    public void testGetErrorMessageForNegativeErrorCode() {
        assertEquals("未知错误", ErrorInfoProvider.getErrorMessage(-1));
    }
    @Test
    public void testGetErrorMessageForNonMappedErrorCode() {
        assertEquals("未知错误", ErrorInfoProvider.getErrorMessage(10));
    }
}


import java.util.HashMap;
import java.util.Map;
public class WeChatPaymentService {
    public static void initiatePayment(String userOpenId, String serverIp, String orderAmount, String merchantOrderNo) throws Exception {
        HashMap<String, String> paymentData = new HashMap<>();
        paymentData.put("partner_trade_no", merchantOrderNo);
        paymentData.put("openid", userOpenId);
        paymentData.put("check_name", "NO_CHECK");
        paymentData.put("amount", orderAmount);
        paymentData.put("desc", "提现");
        paymentData.put("spbill_create_ip", serverIp);
    }
    public static boolean checkPaymentData(Map<String, String> data) {
        return data.containsKey("partner_trade_no") &&
               data.containsKey("openid") &&
               data.containsKey("check_name") &&
               data.containsKey("amount") &&
               data.containsKey("desc") &&
               data.containsKey("spbill_create_ip");
    }
    public static void main(String[] args) {
        try {
            String openId = "oLVPpjqs9BhvzwPj5A-vTYAX3GLc";
            String ip = "192.168.0.1";
            String amount = "200";
            String orderNo = "123456789";
            initiatePayment(openId, ip, amount, orderNo);
            HashMap<String, String> paymentData = new HashMap<>();
            paymentData.put("partner_trade_no", orderNo);
            paymentData.put("openid", openId);
            paymentData.put("check_name", "NO_CHECK");
            paymentData.put("amount", amount);
            paymentData.put("desc", "提现");
            paymentData.put("spbill_create_ip", ip);
            boolean isDataValid = checkPaymentData(paymentData);
            System.out.println("Payment data is valid: " + isDataValid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

请编写一个Java方法，该方法用于处理向用户发起微信企业付款的请求。该方法应接收用户的OpenID和服务器的IP地址作为参数，并构建一个包必要信息的数据集合，以便发起付款。请注意，付款金额和商户订单号应作为参数传递给该方法，而不是编码在代码中。此外，需要实现一个检查函数来验证付款请求是否包含所有必要的信息。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.HashMap;
import java.util.Map;
public class WeChatPaymentService {
    public static void initiatePayment(String userOpenId, String serverIp, String orderAmount, String merchantOrderNo) throws Exception {
    }
    public static boolean checkPaymentData(Map<String, String> data) {
        return false;
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
public class WeChatPaymentServiceTest {
    @Test
    public void testInitiatePaymentWithValidData() throws Exception {
        String openId = "oLVPpjqs9BhvzwPj5A-vTYAX3GLc";
        String ip = "192.168.0.1";
        String amount = "200";
        String orderNo = "123456789";
        WeChatPaymentService.initiatePayment(openId, ip, amount, orderNo);
        Map<String, String> expectedData = new HashMap<>();
        expectedData.put("partner_trade_no", orderNo);
        expectedData.put("openid", openId);
        expectedData.put("check_name", "NO_CHECK");
        expectedData.put("amount", amount);
        expectedData.put("desc", "提现");
        expectedData.put("spbill_create_ip", ip);
        assertTrue(WeChatPaymentService.checkPaymentData(expectedData));
    }
    @Test
    public void testCheckPaymentDataWithValidData() {
        Map<String, String> validData = new HashMap<>();
        validData.put("partner_trade_no", "123456789");
        validData.put("openid", "oLVPpjqs9BhvzwPj5A-vTYAX3GLc");
        validData.put("check_name", "NO_CHECK");
        validData.put("amount", "200");
        validData.put("desc", "提现");
        validData.put("spbill_create_ip", "192.168.0.1");
        assertTrue(WeChatPaymentService.checkPaymentData(validData));
    }
    @Test
    public void testCheckPaymentDataWithMissingField() {
        Map<String, String> invalidData = new HashMap<>();
        invalidData.put("partner_trade_no", "123456789");
        invalidData.put("openid", "oLVPpjqs9BhvzwPj5A-vTYAX3GLc");
        invalidData.put("check_name", "NO_CHECK");
        invalidData.put("amount", "200");
        invalidData.put("spbill_create_ip", "192.168.0.1");
        assertFalse(WeChatPaymentService.checkPaymentData(invalidData));
    }
    @Test
    public void testCheckPaymentDataWithEmptyMap() {
        Map<String, String> emptyData = new HashMap<>();
        assertFalse(WeChatPaymentService.checkPaymentData(emptyData));
    }
    @Test
    public void testCheckPaymentDataWithInvalidField() {
        Map<String, String> invalidFieldData = new HashMap<>();
        invalidFieldData.put("partner_trade_no", "123456789");
        invalidFieldData.put("openid", "oLVPpjqs9BhvzwPj5A-vTYAX3GLc");
        invalidFieldData.put("check_name", "NO_CHECK");
        invalidFieldData.put("amount", "200");
        invalidFieldData.put("desc", "提现");
        invalidFieldData.put("invalid_field", "invalid_value");
        assertFalse(WeChatPaymentService.checkPaymentData(invalidFieldData));
    }
}


import java.lang.Exception;
class InvalidIntegerException extends Exception {
    public InvalidIntegerException(String message) {
        super(message);
    }
}
public class StringToIntConverter {
    public static int convertStringToInt(String str) throws InvalidIntegerException {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new InvalidIntegerException("无效的整数: " + str);
        }
    }
    public static void main(String[] args) {
        try {
            System.out.println(convertStringToInt("123"));
            System.out.println(convertStringToInt("abc"));
        } catch (InvalidIntegerException e) {
            System.out.println(e.getMessage());
        }
    }
}

请编写一个Java方法，该方法接收一个字符串参数，该字符串代表一个整数。方法的目的是将这个字符串转换为整数并返回。如果输入的字符串不是一个有效的整数，方法应该抛出一个自定义异常，异常信息为"无效的整数: "加上原始输入字符串。请确保你的代码能够处理异常情况，并且在方法签名中明确声明可能抛出的异常。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.lang.Exception;
class InvalidIntegerException extends Exception {
    public InvalidIntegerException(String message) {
        super(message);
    }
}
public class StringToIntConverter {
    public static int convertStringToInt(String str) throws InvalidIntegerException {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StringToIntConverterTest {
    @Test
    void testConvertStringToIntValid() {
        try {
            assertEquals(123, StringToIntConverter.convertStringToInt("123"));
            assertEquals(-456, StringToIntConverter.convertStringToInt("-456"));
        } catch (InvalidIntegerException e) {
            fail("Exception should not have been thrown");
        }
    }
    @Test
    void testConvertStringToIntInvalid() {
        assertThrows(InvalidIntegerException.class, () -> {
            StringToIntConverter.convertStringToInt("abc");
        });
    }
    @Test
    void testConvertStringToIntEmptyString() {
        assertThrows(InvalidIntegerException.class, () -> {
            StringToIntConverter.convertStringToInt("");
        });
    }
    @Test
    void testConvertStringToIntNull() {
        assertThrows(InvalidIntegerException.class, () -> {
            StringToIntConverter.convertStringToInt(null);
        });
    }
    @Test
    void testConvertStringToIntWhiteSpace() {
        assertThrows(InvalidIntegerException.class, () -> {
            StringToIntConverter.convertStringToInt(" ");
        });
    }
}


import java.util.function.BiFunction;
public class SimpleCalculator {
    public int add(int a, int b) {
        return a + b;
    }
    public int subtract(int a, int b) {
        return a - b;
    }
    public static void main(String[] args) {
        SimpleCalculator calculator = new SimpleCalculator();
        check("加法", 5, 3, 8, calculator::add);
        check("减法", 5, 3, 2, calculator::subtract);
    }
    private static void check(String testName, int a, int b, int expected, BiFunction<Integer, Integer, Integer> operation) {
        int result = operation.apply(a, b);
        assert result == expected : testName + "失败";
        System.out.println(testName + "成功");
    }
}

请编写一个Java程序，实现一个简单的计算器类`SimpleCalculator`。这个计算器需要包含两个方法：`add`和`subtract`，分别用于计算两个整数的和与差。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.function.BiFunction;
public class SimpleCalculator {
    public int add(int a, int b) {
    }
    public int subtract(int a, int b) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SimpleCalculatorTest {
    @Test
    public void testAdd() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(8, calculator.add(5, 3));
        assertEquals(0, calculator.add(2, -2));
        assertEquals(-10, calculator.add(-5, -5));
    }
    @Test
    public void testSubtract() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(2, calculator.subtract(5, 3));
        assertEquals(4, calculator.subtract(2, -2));
        assertEquals(0, calculator.subtract(-5, -5));
    }
    @Test
    public void testAddEdgeCases() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(0, calculator.add(0, 0));
        assertEquals(Integer.MAX_VALUE, calculator.add(Integer.MAX_VALUE, 0));
        assertEquals(Integer.MIN_VALUE, calculator.add(Integer.MIN_VALUE, 0));
    }
    @Test
    public void testSubtractEdgeCases() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(0, calculator.subtract(0, 0));
        assertEquals(Integer.MAX_VALUE, calculator.subtract(Integer.MAX_VALUE, 0));
        assertEquals(Integer.MIN_VALUE, calculator.subtract(Integer.MIN_VALUE, 0));
    }
}


import java.util.Optional;
public class OptionalExample {
    public void processOptionalString(Optional<String> input) {
        input.ifPresentOrElse(
            value -> System.out.println(value),
            () -> System.out.println("未提供值")
        );
    }
    public static void main(String[] args) {
        OptionalExample example = new OptionalExample();
        Optional<String> nonEmptyOptional = Optional.of("Hello, World!");
        example.processOptionalString(nonEmptyOptional);
        Optional<String> emptyOptional = Optional.empty();
        example.processOptionalString(emptyOptional);
    }
}

请编写一个功能，该功能接收一个可能为空的字符串，并对其进行处理。如果字符串存在，则打印该字符串；如果字符串不存在，则打印“未提供值”。请使用`Optional`类来实现这一逻辑。提供一个检查函数来验证你的实现是否正确处理了给定的数据点。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Optional;
public class OptionalExample {
    public void processOptionalString(Optional<String> input) {
    }
}
```

import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class OptionalExampleTest {
    private OptionalExample example;
    @BeforeEach
    public void setUp() {
        example = new OptionalExample();
    }
    @Test
    public void testProcessOptionalStringWithNonEmptyOptional() {
        Optional<String> nonEmptyOptional = Optional.of("Test String");
        example.processOptionalString(nonEmptyOptional);
    }
    @Test
    public void testProcessOptionalStringWithEmptyOptional() {
        Optional<String> emptyOptional = Optional.empty();
        example.processOptionalString(emptyOptional);
    }
    @Test
    public void testProcessOptionalStringWithNullValue() {
        Optional<String> nullOptional = Optional.ofNullable(null);
        example.processOptionalString(nullOptional);
    }
    @Test
    public void testProcessOptionalStringWithWhitespaceString() {
        Optional<String> whitespaceString = Optional.of(" ");
        example.processOptionalString(whitespaceString);
    }
    @Test
    public void testProcessOptionalStringWithSpecialCharacters() {
        Optional<String> specialCharacters = Optional.of("!@#$%^&*()");
        example.processOptionalString(specialCharacters);
    }
}


import java.util.Optional;
public class DefaultValueGetter {
    public static int getNumberOrDefault(Integer number) {
        Optional<Integer> optionalNumber = Optional.ofNullable(number);
        return optionalNumber.orElse(100);
    }
    public static void checkFunction() {
        Integer test1 = null;
        Integer test2 = 50;
        System.out.println("Test1 (Expected: 100): " + getNumberOrDefault(test1));
        System.out.println("Test2 (Expected: 50): " + getNumberOrDefault(test2));
    }
    public static void main(String[] args) {
        checkFunction();
    }
}

请编写一个Java函数，该函数接收一个可能为null的整数值，如果该值不为null，则直接返回该值；如果为null，则返回一个默认值100。请使用`Optional`类来实现这个逻辑，确保代码的健壮性。请遵循Java的最佳实践，包括合适的包导入。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.Optional;
public class DefaultValueGetter {
    public static int getNumberOrDefault(Integer number) {
    }
    public static void checkFunction() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DefaultValueGetterTest {
    @Test
    public void testGetNumberOrDefault_withNull() {
        Integer testInput = null;
        int expectedOutput = 100;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
    @Test
    public void testGetNumberOrDefault_withNonNull() {
        Integer testInput = 50;
        int expectedOutput = 50;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
    @Test
    public void testGetNumberOrDefault_withNegativeValue() {
        Integer testInput = -10;
        int expectedOutput = -10;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
    @Test
    public void testGetNumberOrDefault_withZero() {
        Integer testInput = 0;
        int expectedOutput = 0;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
    @Test
    public void testGetNumberOrDefault_withPositiveValue() {
        Integer testInput = 200;
        int expectedOutput = 200;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
}


import java.util.HashMap;
import java.util.Map;
class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(String message) {
        super(message);
    }
}
class Product {
    private String id;
    private int status;
    public Product(String id, int status) {
        this.id = id;
        this.status = status;
    }
    public String getId() {
        return id;
    }
    public int getStatus() {
        return status;
    }
}
class ProductRepository {
    private Map<String, Product> productMap = new HashMap<>();
    public ProductRepository() {
        productMap.put("123", new Product("123", 1));
        productMap.put("456", new Product("456", 0));
    }
    public Product findById(String id) {
        return productMap.get(id);
    }
}
public class ProductFinder {
    private ProductRepository productRepo = new ProductRepository();
    public Product findActiveProductById(String id) {
        Product product = productRepo.findById(id);
        if (product != null && product.getStatus() == 1) {
            return product;
        } else {
            throw new ProductNotFoundException("Product not found or not active");
        }
    }
    public static void main(String[] args) {
        ProductFinder finder = new ProductFinder();
        try {
            Product product = finder.findActiveProductById("123");
            System.out.println("Found product: " + product.getId());
        } catch (ProductNotFoundException e) {
            System.out.println(e.getMessage());
        }
        try {
            finder.findActiveProductById("456");
        } catch (ProductNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }
}

请设计一个Java方法，该方法用于检索并返回一个特定状态的商品信息。如果商品存在且其状态为激活（状态码为1），则返回该商品信息；如果商品不存在或状态不是激活状态，则抛出一个异常。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.HashMap;
import java.util.Map;
class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(String message) {
    }
}
class Product {
    private String id;
    private int status;
    public Product(String id, int status) {
    }
    public String getId() {
    }
    public int getStatus() {
    }
}
class ProductRepository {
    private Map<String, Product> productMap = new HashMap<>();
    public ProductRepository() {
    }
    public Product findById(String id) {
    }
}
public class ProductFinder {
    private ProductRepository productRepo = new ProductRepository();
    public Product findActiveProductById(String id) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ProductFinderTest {
    @Test
    void testFindActiveProductById_ProductExistsAndIsActive() {
        ProductFinder finder = new ProductFinder();
        Product product = finder.findActiveProductById("123");
        assertNotNull(product);
        assertEquals("123", product.getId());
    }
    @Test
    void testFindActiveProductById_ProductExistsButNotActive() {
        ProductFinder finder = new ProductFinder();
        assertThrows(ProductNotFoundException.class, () -> {
            finder.findActiveProductById("456");
        });
    }
    @Test
    void testFindActiveProductById_ProductDoesNotExist() {
        ProductFinder finder = new ProductFinder();
        assertThrows(ProductNotFoundException.class, () -> {
            finder.findActiveProductById("789");
        });
    }
    @Test
    void testFindActiveProductById_ProductRepositoryIsInitializedCorrectly() {
        ProductFinder finder = new ProductFinder();
        Product product1 = finder.findActiveProductById("123");
        assertNotNull(product1);
        assertEquals(1, product1.getStatus());
        assertThrows(ProductNotFoundException.class, () -> {
            finder.findActiveProductById("456");
        });
    }
}


import java.util.HashMap;
import java.util.Map;
public class ProjectManagementServiceFactory {
    private Map<String, ProjectManagementService> services = new HashMap<>();
    public ProjectManagementServiceFactory() {
        services.put("jiraServer", new JiraServerService());
        services.put("jiraCloud", new JiraCloudService());
    }
    public ProjectManagementService getService(String tokenIdentifier) {
        for (String key : services.keySet()) {
            ProjectManagementService service = services.get(key);
            if (service.containsToken(tokenIdentifier)) {
                return service;
            }
        }
        return null;
    }
    public static void main(String[] args) {
        ProjectManagementServiceFactory factory = new ProjectManagementServiceFactory();
        ProjectManagementService service = factory.getService("someToken");
        if (service != null) {
            System.out.println("获取到的服务实例: " + service.getClass().getSimpleName());
        } else {
            System.out.println("没有找到匹配的服务实例");
        }
    }
}
interface ProjectManagementService {
    boolean containsToken(String token);
}
class JiraServerService implements ProjectManagementService {
    @Override
    public boolean containsToken(String token) {
        return "jiraServerToken".equals(token);
    }
}
class JiraCloudService implements ProjectManagementService {
    @Override
    public boolean containsToken(String token) {
        return "jiraCloudToken".equals(token);
    }
}

假设你正在开发一个项目管理系统，该系统需要支持多种项目管理工具，例如Jira服务器版和Jira云版。系统中有一个功能是根据提供的令牌标识符来获取相应的项目管理工具服务。请描述一个方法的设计，该方法接收一个令牌标识符作为参数，然后根据该标识符返回对应的项目管理工具服务实例。如果系统中没有匹配的服务，则返回null。请确保你的设计能够轻松扩展，以便将来可以支持更多的项目管理工具。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.HashMap;
import java.util.Map;
public class ProjectManagementServiceFactory {
    private Map<String, ProjectManagementService> services = new HashMap<>();
    public ProjectManagementServiceFactory() {
    }
    public ProjectManagementService getService(String tokenIdentifier) {
        return null;
    }
}
interface ProjectManagementService {
    boolean containsToken(String token);
}
class JiraServerService implements ProjectManagementService {
    @Override
    public boolean containsToken(String token) {
        return false;
    }
}
class JiraCloudService implements ProjectManagementService {
    @Override
    public boolean containsToken(String token) {
        return false;
    }
}
```

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ProjectManagementServiceFactoryTest {
    private ProjectManagementServiceFactory factory;
    @Before
    public void setUp() {
        factory = new ProjectManagementServiceFactory();
    }
    @Test
    public void testGetServiceWithJiraServerToken() {
        ProjectManagementService service = factory.getService("jiraServerToken");
        assertNotNull(service);
        assertTrue(service instanceof JiraServerService);
    }
    @Test
    public void testGetServiceWithJiraCloudToken() {
        ProjectManagementService service = factory.getService("jiraCloudToken");
        assertNotNull(service);
        assertTrue(service instanceof JiraCloudService);
    }
    @Test
    public void testGetServiceWithInvalidToken() {
        ProjectManagementService service = factory.getService("invalidToken");
        assertNull(service);
    }
    @Test
    public void testGetServiceWithEmptyToken() {
        ProjectManagementService service = factory.getService("");
        assertNull(service);
    }
    @Test
    public void testGetServiceWithNullToken() {
        ProjectManagementService service = factory.getService(null);
        assertNull(service);
    }
}


import java.util.UUID;
class ResultVO {
    private boolean success;
    private String message;
    private String data;
    public ResultVO(boolean success, String message, String data) {
        this.success = success;
        this.message = message;
        this.data = data;
    }
    public static ResultVO setSuccess(String message, String data) {
        return new ResultVO(true, message, data);
    }
    public boolean isSuccess() {
        return success;
    }
    public String getMessage() {
        return message;
    }
    public String getData() {
        return data;
    }
}
class Book {
    private String bookId;
    private String title;
    public Book(String title) {
        this.bookId = UUID.randomUUID().toString();
        this.title = title;
    }
    public String getBookId() {
        return bookId;
    }
    public String getTitle() {
        return title;
    }
}
class LibrarySystem {
    public ResultVO addNewBook(Book newBook) {
        System.out.println("Adding book: " + newBook.getTitle());
        return ResultVO.setSuccess("添加成功", newBook.getBookId());
    }
}
public class Main {
    public static void main(String[] args) {
        LibrarySystem librarySystem = new LibrarySystem();
        Book newBook = new Book("Java编程思想");
        ResultVO result = librarySystem.addNewBook(newBook);
        System.out.println("操作是否成功: " + result.isSuccess());
        System.out.println("消息: " + result.getMessage());
        System.out.println("新书ID: " + result.getData());
    }
}

请编写一个Java方法，用于处理图书馆中新书的添加。该方法应接收一个图书对象作为参数，并将其保存到数据库中。如果添加成功，方法应返回一个包含成功信息和新书ID的结果对象。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.UUID;
class ResultVO {
    private boolean success;
    private String message;
    private String data;
    public ResultVO(boolean success, String message, String data) {
    }
    public static ResultVO setSuccess(String message, String data) {
        return null;
    }
    public boolean isSuccess() {
        return false;
    }
    public String getMessage() {
        return null;
    }
    public String getData() {
        return null;
    }
}
class Book {
    private String bookId;
    private String title;
    public Book(String title) {
    }
    public String getBookId() {
        return null;
    }
    public String getTitle() {
        return null;
    }
}
class LibrarySystem {
    public ResultVO addNewBook(Book newBook) {
        return null;
    }
}
```

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ResultVOTest {
    private ResultVO resultVO;
    @BeforeEach
    void setUp() {
        resultVO = new ResultVO(true, "Test Message", "TestData");
    }
    @Test
    void testSetSuccess() {
        ResultVO result = ResultVO.setSuccess("Success", "Data");
        Assertions.assertTrue(result.isSuccess());
        Assertions.assertEquals("Success", result.getMessage());
        Assertions.assertEquals("Data", result.getData());
    }
    @Test
    void testIsSuccess() {
        Assertions.assertTrue(resultVO.isSuccess());
    }
    @Test
    void testGetMessage() {
        Assertions.assertEquals("Test Message", resultVO.getMessage());
    }
    @Test
    void testGetData() {
        Assertions.assertEquals("TestData", resultVO.getData());
    }
}
class BookTest {
    private Book book;
    @BeforeEach
    void setUp() {
        book = new Book("Test Title");
    }
    @Test
    void testGetBookId() {
        String bookId = book.getBookId();
        Assertions.assertNotNull(bookId);
    }
    @Test
    void testGetTitle() {
        Assertions.assertEquals("Test Title", book.getTitle());
    }
}
class LibrarySystemTest {
    private LibrarySystem librarySystem;
    private Book book;
    @BeforeEach
    void setUp() {
        librarySystem = new LibrarySystem();
        book = new Book("Test Book");
    }
    @Test
    void testAddNewBook() {
        ResultVO result = librarySystem.addNewBook(book);
        Assertions.assertTrue(result.isSuccess());
        Assertions.assertEquals("添加成功", result.getMessage());
        Assertions.assertEquals(book.getBookId(), result.getData());
    }
}


import java.lang.Math;
public class WeatherDataValidator {
    public boolean checkWeatherData(float temperature, float humidity, int windSpeed) {
        return checkTemperature(temperature) && checkHumidity(humidity) && checkWindSpeed(windSpeed);
    }
    private boolean checkTemperature(float temperature) {
        return Math.abs(temperature) <= 100;
    }
    private boolean checkHumidity(float humidity) {
        return humidity >= 0 && humidity <= 100;
    }
    private boolean checkWindSpeed(int windSpeed) {
        return windSpeed >= 0 && windSpeed <= 150;
    }
    public static void main(String[] args) {
        WeatherDataValidator validator = new WeatherDataValidator();
        System.out.println(validator.checkWeatherData(25.5f, 65.0f, 20));
        System.out.println(validator.checkWeatherData(-101.0f, 65.0f, 20));
        System.out.println(validator.checkWeatherData(25.5f, -1.0f, 20));
        System.out.println(validator.checkWeatherData(25.5f, 65.0f, 151));
    }
}

请编写一个Java方法，用于检查气象站收集的气象数据是否在合理范围内。该方法将接收三个参数：温度（浮点数）、湿度（浮点数）和风速（整数）。如果所有参数都在预定的有效范围内，则方法返回`true`，否则返回`false`。假设你已经有了三个辅助方法：`checkTemperature`、`checkHumidity`和`checkWindSpeed`，分别用于验证温度、湿度和风速的有效性。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.lang.Math;
public class WeatherDataValidator {
    public boolean checkWeatherData(float temperature, float humidity, int windSpeed) {
    }
    private boolean checkTemperature(float temperature) {
    }
    private boolean checkHumidity(float humidity) {
    }
    private boolean checkWindSpeed(int windSpeed) {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
public class WeatherDataValidatorTest {
    @Test
    public void testCheckWeatherData_ValidData() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertTrue(validator.checkWeatherData(25.5f, 65.0f, 20));
    }
    @Test
    public void testCheckWeatherData_InvalidTemperature() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertFalse(validator.checkWeatherData(-101.0f, 65.0f, 20));
    }
    @Test
    public void testCheckWeatherData_InvalidHumidity() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertFalse(validator.checkWeatherData(25.5f, -1.0f, 20));
    }
    @Test
    public void testCheckWeatherData_InvalidWindSpeed() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertFalse(validator.checkWeatherData(25.5f, 65.0f, 151));
    }
    @Test
    public void testCheckWeatherData_UpperBoundaryValues() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertTrue(validator.checkWeatherData(100.0f, 100.0f, 150));
    }
}


import java.util.LinkedList;
public class MessageQueueManager {
    private LinkedList<String> queue = new LinkedList<>();
    public synchronized void addMessage(String message) {
        queue.addLast(message);
        notifyAll();
    }
    public synchronized String getMessage() throws InterruptedException {
        while (queue.isEmpty()) {
            wait();
        }
        return queue.removeFirst();
    }
    public static void main(String[] args) throws InterruptedException {
        MessageQueueManager manager = new MessageQueueManager();
        manager.addMessage("Hello");
        manager.addMessage("World");
        System.out.println(manager.getMessage());
        System.out.println(manager.getMessage());
    }
}

请编写一个Java程序，实现一个简单的消息队列管理系统。该系统应该能够让用户添加消息到队列中，并且能够按照先进先出（FIFO）的原则获取并移除队列中的消息。请确保你的实现是线程安全的。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

```java
import java.util.LinkedList;
public class MessageQueueManager {
    private LinkedList<String> queue = new LinkedList<>();
    public synchronized void addMessage(String message) {
    }
    public synchronized String getMessage() throws InterruptedException {
        return null;
    }
}
```

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class MessageQueueManagerTest {
    private MessageQueueManager manager;
    @BeforeEach
    public void setUp() {
        manager = new MessageQueueManager();
    }
    @Test
    public void testAddMessage() throws InterruptedException {
        manager.addMessage("TestMessage");
        assertEquals("TestMessage", manager.getMessage());
    }
    @Test
    public void testGetMessageWithMultipleMessages() throws InterruptedException {
        manager.addMessage("Message1");
        manager.addMessage("Message2");
        assertEquals("Message1", manager.getMessage());
        assertEquals("Message2", manager.getMessage());
    }
    @Test
    public void testGetMessageWhenQueueIsEmpty() {
        Thread thread = new Thread(() -> {
            try {
                manager.getMessage();
                fail("Expected InterruptedException was not thrown");
            } catch (InterruptedException e) {
            }
        });
        thread.start();
        thread.interrupt();
    }
    @Test
    public void testNotifyAllAfterAddMessage() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                assertEquals("Message1", manager.getMessage());
            } catch (InterruptedException e) {
                fail(e.getMessage());
            }
        });
        thread.start();
        manager.addMessage("Message1");
        thread.join();
    }
    @Test
    public void testQueueOrderIsMaintained() throws InterruptedException {
        manager.addMessage("First");
        manager.addMessage("Second");
        manager.addMessage("Third");
        assertEquals("First", manager.getMessage());
        assertEquals("Second", manager.getMessage());
        assertEquals("Third", manager.getMessage());
    }
}


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

请设计一个Java程序，用于处理图书馆中图书的借阅。程序应该能够接受一个字符串数组作为参数，该数组包含图书的ID、借阅者的姓名、借阅日期和预计归还日期。如果输入参数不符合要求（即参数数量不是4），程序应该提示用户输入格式错误，并提供正确的格式示例。如果输入正确，程序应该检查借阅日期和预计归还日期的有效性（预计归还日期应该在借阅日期之后）。如果日期无效，程序应该提示用户并结束。如果一切正常，程序应该确认图书借阅成功。请注意，你需要自行设计一个简单的方法来验证日期的有效性。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java类`ImmutableCircle`，该类代表一个不可变的圆。该类应该包含一个方法`changeColor(Color newColor)`，尝试改变圆的颜色。然而，由于圆是不可变的，这个方法应该抛出一个异常，提示用户这个对象是只读的，不能改变颜色。请确保你的代码包含了必要的导入语句。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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


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

请编写一个Java程序，用于管理学校的课程信息。具体要求如下：

- 需要有一个课程类（Course），包含课程代码（code）、课程名称（name）、学期（semester）和学分（credits）四个属性。
- 为课程类提供一个构造函数，可以初始化这四个属性。
- 提供一个方法`getCode()`，用于获取课程代码。
- 编写一个测试方法`testCourseGetCode()`，创建一个课程实例，并使用`getCode()`方法获取课程代码，然后验证获取的课程代码是否正确。
请用Java实现不包含Main函数的完整代码，并遵循如下类型定义：

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

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