回顾:HashSet
本课属于 Coddy Java 学习旅程的“逻辑与流程”单元。第 28 课,共 59 课。
挑战
简单创建一个名为 processHashSet 的方法,它接受三个参数:
- 一个
HashSet<Object>(set) - 一个要处理的
Object(input) - 一个用于指定要执行操作的
String(operation)
使用 if/else 语句和你已经学过的 HashSet 方法,根据 operation 返回一个 String:
"add":将input添加到集合中。如果添加成功,返回"Added successfully";如果它已在集合中,返回"Element already exists"。"remove":从集合中移除input。如果移除成功,返回"Removed successfully";如果它不在集合中,返回"Element not found"。"find":如果集合包含input,返回"Found at index: [index]"(其中[index]是元素在迭代顺序中的位置);否则返回"Element not found"。"count":返回"Number of elements: [count]",其中[count]是集合中的元素数量(使用size())。
首先验证输入:
- 如果
set为null:返回"Invalid set"。 - 如果
operation为null,或不是以上四种操作之一:返回"Invalid operation"。 - 对于
"find"操作,如果input为null:返回"Cannot find null"。
亲手试试
import java.util.HashSet;
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static String processHashSet(HashSet<Object> set, Object input, String operation) {
// 在这里编写你的代码
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取初始集合
String[] items = scanner.nextLine().split(",");
HashSet<Object> set = new HashSet<>();
if (!items[0].equals("empty")) {
for (String item : items) {
// 先尝试解析为整数
try {
set.add(Integer.parseInt(item));
} catch (NumberFormatException e) {
set.add(item);
}
}
}
// 读取输入
String inputStr = scanner.nextLine();
Object input;
try {
input = Integer.parseInt(inputStr);
} catch (NumberFormatException e) {
input = inputStr;
}
// 读取操作
String operation = scanner.nextLine();
System.out.println(processHashSet(set, input, operation));
}
}逻辑与流程中的所有课
自己练习: Java 在线编译器