Untitled
unknown
java
2 years ago
3.8 kB
9
Indexable
import java.util.*; /** * This class represents a shopping list based on available ingredients and a * recipe. * The user can read ingredient data from the console and get a shopping list to * know which ingredients are missing or insufficient. */ public class ShoppingList { // Flags if currently processing a recipe or available ingredients. private boolean isCheckingRecipe; // TreeMap to store available ingredients and their amounts. private TreeMap<String, Integer> available; // TreeMap to store ingredients required for a recipe and their amounts. private TreeMap<String, Integer> recipe; /** * Default constructor initializes the available ingredients and recipe * TreeMaps. */ public ShoppingList() { available = new TreeMap<>(); recipe = new TreeMap<>(); isCheckingRecipe = false; } /** * Reads ingredient data from the console. * * @param lines Not used in the current implementation. */ public void read(String[] lines) { Scanner scanner = new Scanner(System.in); // Continuously read lines from the console. while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] lineArray = line.split(" "); if (lineArray.length != 3) { continue; } if (lineArray[0].equals("RECIPE")) { isCheckingRecipe = true; continue; } String amountStr = lineArray[0]; String unit = lineArray[1]; String ingredient = lineArray[2]; int amountInGrams; if (unit.equals("kg")) { amountInGrams = kgToG(Integer.parseInt(amountStr)); } else { amountInGrams = Integer.parseInt(amountStr); } if (!isCheckingRecipe) { available.put(ingredient, amountInGrams); } else { recipe.put(ingredient, amountInGrams); } } TreeMap<String, String> shoppingList = createShoppingList(); printShoppingList(shoppingList); } /** * Converts kilograms to grams. * * @param kg Kilograms to convert. * @return The value in grams. */ public int kgToG(int kg) { return kg * 1000; } /** * Creates a shopping list based on available ingredients and a recipe. * * @return A TreeMap representing the shopping list. */ public TreeMap<String, String> createShoppingList() { TreeMap<String, String> shoppingList = new TreeMap<>(); for (String ingredient : recipe.keySet()) { if (available.containsKey(ingredient)) { int availableAmount = available.get(ingredient); int recipeAmount = recipe.get(ingredient); if (availableAmount < recipeAmount) { int amountNeeded = recipeAmount - availableAmount; shoppingList.put(ingredient, "g " + amountNeeded); } } else { shoppingList.put(ingredient, "g " + recipe.get(ingredient)); } } return shoppingList; } /** * Prints the shopping list in the specified format. * * @param shoppingList Shopping list to print. */ private void printShoppingList(TreeMap<String, String> shoppingList) { System.out.println("Shopping List:"); for (Map.Entry<String, String> entry : shoppingList.entrySet()) { System.out.println(entry.getValue() + " " + entry.getKey()); } } }
Editor is loading...