カートへの商品の追加
CoddyのDartジャーニー「論理とフロー」セクションの一部 — レッスン 34/65。
チャレンジ
簡単ショッピングカートにアイテムを追加する機能を実装するプログラムを作成してください。プログラムでは、ハードコードされた商品カタログの Map と空のショッピングカートの List を使用し、ユーザーからのアイテム入力を処理する必要があります。
コード内で以下の商品カタログを直接定義してください:
Map<String, double> productCatalog = {
'Apple': 1.50,
'Banana': 0.80,
'Orange': 2.00,
'Milk': 3.25,
'Laptop': 999.99,
'Mouse': 25.50,
'Keyboard': 75.00,
'Novel': 12.99,
'Magazine': 4.50,
'Textbook': 89.00
};プログラムの要件は以下の通りです:
- 上記で定義した商品カタログの Map と空のショッピングカートの List を使用すること
- 顧客がカートに追加したいアイテムを表す複数の文字列入力を読み取ること(入力は
"cart_done"を受け取った時点で終了します) - 各アイテムについて、
containsKey()を使用して商品カタログに存在するかどうかを確認すること - アイテムが存在する場合は、
add()メソッドを使用してショッピングカートの List に追加すること - アイテムが存在しない場合は、そのアイテムをスキップして処理を続行すること
- 追加に成功した回数と失敗した回数を追跡すること
- カート管理レポートを、以下に示す正確な形式で表示すること
例えば、顧客が "Apple"、"Bread"、"Banana"、"Apple"、"Juice" を追加したい場合、プログラムは以下のように出力する必要があります:
Shopping Cart Operations:
Adding 'Apple': Item added to cart successfully
Adding 'Bread': Item not available in store
Adding 'Banana': Item added to cart successfully
Adding 'Apple': Item added to cart successfully
Adding 'Juice': Item not available in store
Cart Contents: [Apple, Banana, Apple]
Cart Summary:
Total items in cart: 3
Unique products in cart: 2
Items successfully added: 3
Items not found: 2
Cart Status: Ready for checkout顧客が "Mouse"、"Monitor"、"Keyboard"、"Mouse" を追加したい場合、プログラムは以下のように出力する必要があります:
Shopping Cart Operations:
Adding 'Mouse': Item added to cart successfully
Adding 'Monitor': Item not available in store
Adding 'Keyboard': Item added to cart successfully
Adding 'Mouse': Item added to cart successfully
Cart Contents: [Mouse, Keyboard, Mouse]
Cart Summary:
Total items in cart: 3
Unique products in cart: 2
Items successfully added: 3
Items not found: 1
Cart Status: Ready for checkout顧客が "Novel"、"Dictionary"、"Magazine"、"Novel"、"Comic"、"Textbook" を追加したい場合、プログラムは以下のように出力する必要があります:
Shopping Cart Operations:
Adding 'Novel': Item added to cart successfully
Adding 'Dictionary': Item not available in store
Adding 'Magazine': Item added to cart successfully
Adding 'Novel': Item added to cart successfully
Adding 'Comic': Item not available in store
Adding 'Textbook': Item added to cart successfully
Cart Contents: [Novel, Magazine, Novel, Textbook]
Cart Summary:
Total items in cart: 4
Unique products in cart: 3
Items successfully added: 4
Items not found: 2
Cart Status: Ready for checkoutプログラムでは、カートに追加する前に containsKey() を使用して各アイテムが商品カタログに存在することを確認する必要があります。有効なアイテムをショッピングカートの List に追加するには add() メソッドを使用してください。カート内の総アイテム数は length プロパティを使用してカウントし、ユニークな商品数はカートを Set に変換してその長さを確認することで特定してください。追加に成功したアイテムとカタログに見つからなかったアイテムの両方を追跡してください。入力形式は、カートに追加するアイテム名で、最後に "cart_done" が入力されます。
自分で試してみよう
import 'dart:io';
void main() {
// Read store name
String? storeName = stdin.readLineSync();
// Initialize data structures
Map<String, double> products = {};
List<String> shoppingCart = [];
// Read products until "products_done"
while (true) {
String? input = stdin.readLineSync();
if (input == "products_done") {
break;
}
String productName = input!;
String? priceInput = stdin.readLineSync();
double price = double.parse(priceInput!);
// Add product to map
products[productName] = price;
}
// Calculate statistics
double totalPrice = 0;
double maxPrice = 0;
double minPrice = double.infinity;
String mostExpensiveItem = '';
String cheapestItem = '';
for (String productName in products.keys) {
double price = products[productName]!;
totalPrice += price;
if (price > maxPrice) {
maxPrice = price;
mostExpensiveItem = productName;
}
if (price < minPrice) {
minPrice = price;
cheapestItem = productName;
}
}
double averagePrice = totalPrice / products.length;
// Print the store setup report
print('Store: $storeName');
print('Product Catalog Setup:');
print('Available Products: $products');
print('Shopping Cart Initialized: $shoppingCart');
print('System Status:');
print('Total products available: ${products.length}');
print('Cart status: Empty');
print('Most expensive item: $mostExpensiveItem (\$${maxPrice.toStringAsFixed(2)})');
print('Cheapest item: $cheapestItem (\$${minPrice.toStringAsFixed(2)})');
print('Average product price: \$${averagePrice.toStringAsFixed(2)}');
print('Setup Status: Shopping cart system ready for customers');
}論理とフローのすべてのレッスン
1リスト操作の応用
リストのプロパティ: first と lastリストの状態: isEmpty と isNotEmptyリストの反転リストへの追加: insertリストの削除: removeWhereリスト内の検索: indexOfリストのソートリストのシャッフルまとめ - リストオーガナイザー