復習 - 倉庫管理
CoddyのJavaジャーニー「ロジックとフロー」セクションの一部 — レッスン 20/59。
チャレンジ
簡単<strong>manageWarehouse</strong> という名前のメソッドを作成し、2つの引数を受け取るようにしてください:
- warehouse という名前の HashMap で:
- キーは商品名を表します(
String)。 - 値は数量を表します(
Integer)。
- キーは商品名を表します(
- 操作のリスト(
<strong>String[] operations</strong>)で、各文字列は以下の形式のいずれかに従います:"ADD product quantity"→ 指定された数量を既存の商品に追加します(存在しない場合は作成します)。"REMOVE product quantity"→ 商品の数量を減少させます。数量が0 または負になった場合、商品を削除します。"CHECK product"→ 商品が存在する場合はtrueを出力し、そうでなければfalseを出力します。"PRINT"→ すべての商品とその数量を以下の形式で出力します:Product: Laptop, Quantity: 10 Product: Mouse, Quantity: 50
String を Integer に変換するには、以下を使用します:
String quantityString = "25";
int quantity = Integer.valueOf(quantityString);
System.out.println(quantity + 5); // Output: 30Integer.valueOf() は、計算に使用できる整数を取得することを保証します。
自分で試してみよう
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) {
// ここにコードを書いてください
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String warehouseString = scanner.nextLine();
String operationsString = scanner.nextLine();
// JSON文字列をHashMapに変換
Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
HashMap<String, Integer> warehouse = new Gson().fromJson(warehouseString, mapType);
// JSON文字列を配列に変換
String[] operations = new Gson().fromJson(operationsString, String[].class);
manageWarehouse(warehouse, operations);
}
}