장바구니에 항목 추가하기
Coddy Dart 여정의 로직 & 흐름 섹션에 포함된 레슨 — 65개 중 34번째.
챌린지
쉬움쇼핑 카트에 품목을 추가하는 기능을 구현하는 프로그램을 작성하세요. 프로그램은 코드 내에 고정된 제품 카탈로그 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리스트 정렬리스트 섞기요약 - 리스트 정리 도구