Menu
Coddy logo textTech

Recap - Manage Warehouse

Part of the Logic & Flow section of Coddy's Java journey — lesson 20 of 59.

challenge icon

Challenge

Easy

Create a method named <strong>manageWarehouse</strong> that takes two arguments:

  1. A HashMap named <strong>warehouse</strong> where:
    • Keys represent product names (String).
    • Values represent quantities (Integer).
  2. A list of operations (<strong>String[] operations</strong>) where each string follows one of these formats:
    • "ADD product quantity" → Adds the given quantity to the existing product (or creates it if not present).
    • "REMOVE product quantity" → Decreases the quantity of the product. If quantity becomes 0 or negative, remove the product.
    • "CHECK product" → Prints true if the product exists, otherwise false.
    • "PRINT" → Prints all products and their quantities in the format:

      Product: Laptop, Quantity: 10
      Product: Mouse, Quantity: 50

To convert a String into an Integer, we use:

String quantityString = "25";  
int quantity = Integer.valueOf(quantityString);  
System.out.println(quantity + 5); // Output: 30

Integer.valueOf() ensures we get an integer that we can use in calculations.

Try it yourself

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void manageWarehouse(HashMap<String, Integer> warehouse, String[] operations) {
        // Write your code here
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String warehouseString = scanner.nextLine();
        String operationsString = scanner.nextLine();

        // Convert JSON string to HashMap
        Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
        HashMap<String, Integer> warehouse = new Gson().fromJson(warehouseString, mapType);

        // Convert JSON string to Array
        String[] operations = new Gson().fromJson(operationsString, String[].class);

        manageWarehouse(warehouse, operations);
    }
}

All lessons in Logic & Flow