復習 - 倉庫管理
CoddyのJavaジャーニー「ロジックとフロー」セクションの一部。レッスン 20/59。
チャレンジ
簡単manageWarehouseという名前のメソッドを作成します。このメソッドは2つの引数を受け取ります。
- 次の条件を満たす、
warehouseという名前のHashMap:- キーは商品名(
String)を表します。 - 値は数量(
Integer)を表します。
- キーは商品名(
- 操作のリスト(
String[] operations)。各文字列は次のいずれかの形式です。"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文字列をArrayに変換する
String[] operations = new Gson().fromJson(operationsString, String[].class);
manageWarehouse(warehouse, operations);
}
}ロジックとフローのすべてのレッスン
自分で練習してみよう: Javaオンラインコンパイラ