Menu
Coddy logo textTech

요약 - HashSet

Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨. 59개 중 28번째.

challenge icon

챌린지

쉬움

processHashSet라는 이름의 메서드를 만들고 다음 세 가지 인수를 받도록 하세요:

  1. HashSet<Object>(set)
  2. 처리할 Object(input)
  3. 수행할 작업을 지정하는 String(operation)

if/else 문과 이미 배운 HashSet 메서드를 사용하여, 메서드는 operation에 따라 String을 return해야 합니다:

  • "add": input을 set에 추가합니다. 추가되었으면 "Added successfully"를, 이미 set에 있었다면 "Element already exists"를 return합니다.
  • "remove": set에서 input을 제거합니다. 제거되었으면 "Removed successfully"를, set에 없었다면 "Element not found"를 return합니다.
  • "find": set에 input이 포함되어 있으면 "Found at index: [index]"를 return합니다. 여기서 [index]는 반복 순서에서 해당 요소의 위치입니다. 포함되어 있지 않으면 "Element not found"를 return합니다.
  • "count": "Number of elements: [count]"를 return합니다. 여기서 [count]는 set의 요소 개수입니다(size()를 사용하세요).

먼저 입력을 Validate하세요:

  • setnull인 경우: "Invalid set"을 return합니다.
  • operationnull이거나 위의 네 가지 중 하나가 아닌 경우: "Invalid operation"을 return합니다.
  • "find" operation에서 inputnull인 경우: "Cannot find null"을 return합니다.

직접 해보기

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 컴파일러