Menu
Coddy logo textTech

Ripasso - HashSet

Fa parte della sezione Logica e flusso del percorso Java di Coddy. Lezione 28 di 59.

challenge icon

Sfida

Facile

Crea un metodo chiamato processHashSet che accetta tre argomenti:

  1. Un HashSet<Object> (set)
  2. Un Object (input) da elaborare
  3. Una String (operation) che specifica l’operazione da eseguire

Usando istruzioni if/else e i metodi di HashSet che hai già imparato, il metodo dovrebbe restituire una String in base a operation:

  • "add": aggiungi input al set. Restituisci "Added successfully" se è stato aggiunto, oppure "Element already exists" se era già presente nel set.
  • "remove": rimuovi input dal set. Restituisci "Removed successfully" se è stato rimosso, oppure "Element not found" se non era presente nel set.
  • "find": restituisci "Found at index: [index]" se il set contiene input (dove [index] è la posizione dell’elemento nell’ordine di iterazione), altrimenti "Element not found".
  • "count": restituisci "Number of elements: [count]", dove [count] è il numero di elementi nel set (usa size()).

Convalida prima gli input:

  • Se set è null: restituisci "Invalid set".
  • Se operation è null o non è una delle quattro operazioni indicate sopra: restituisci "Invalid operation".
  • Per l’operazione "find", se input è null: restituisci "Cannot find null".

Provalo tu

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) {
        // Scrivi qui il tuo codice
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Leggi l'insieme iniziale
        String[] items = scanner.nextLine().split(",");
        HashSet<Object> set = new HashSet<>();
        if (!items[0].equals("empty")) {
            for (String item : items) {
                // Prova prima a convertire in un intero
                try {
                    set.add(Integer.parseInt(item));
                } catch (NumberFormatException e) {
                    set.add(item);
                }
            }
        }
        
        // Leggi l'input
        String inputStr = scanner.nextLine();
        Object input;
        try {
            input = Integer.parseInt(inputStr);
        } catch (NumberFormatException e) {
            input = inputStr;
        }
        
        // Leggi l'operazione
        String operation = scanner.nextLine();
        
        System.out.println(processHashSet(set, input, operation));
    }
}

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Java online