Menu
Coddy logo textTech

復習 - HashSet

CoddyのJavaジャーニー「ロジックとフロー」セクションの一部 — レッスン 28/59。

challenge icon

チャレンジ

簡単

3つの引数を受け取る processHashSet という名前のメソッドを作成してください:

  1. HashSet<Object> (set)
  2. 処理対象の Object (input)
  3. 実行する操作を指定する 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 integers: [count]" を返します([count] はセット内の整数の数)。

最初に入力値を検証してください:

  • setnull の場合:"Invalid set" を返します。
  • operationnull、または上記の4つのいずれでもない場合:"Invalid operation" を返します。
  • "find" 操作の際、inputnull の場合:"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));
    }
}

ロジックとフローのすべてのレッスン