Recap - Manage Warehouse
Part of the Logic & Flow section of Coddy's Java journey — lesson 20 of 59.
Challenge
EasyCreate a method named <strong>manageWarehouse</strong> that takes two arguments:
- A HashMap named
<strong>warehouse</strong>where:- Keys represent product names (
String). - Values represent quantities (
Integer).
- Keys represent product names (
- 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"→ Printstrueif the product exists, otherwisefalse."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: 30Integer.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
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow