Console Shopping Cart Simulator

A Dart console app simulating a shopping cart with add, remove, view, and total calculation features, demonstrating list management and user input.

Brief Introduction

Console Shopping Cart Simulator (dart)
DESCRIPTION:
A console application written in Dart that simulates a shopping cart. It allows adding, removing, and viewing products with quantities and prices, calculating the total. Useful for understanding list management, user input, and data structures in Dart.

ADDITIONAL NOTES:
The program is designed to run in a console environment. It requires no external libraries, enabling immediate use. It handles user input with basic validation and uses Dart's null safety for greater robustness.

EXPLANATIONS:
- The Product class encapsulates data for a single product, including name, unit price, and quantity, with methods to calculate the product's total price.
- The Cart class maintains a list of products and provides methods to add, remove, modify quantities, and calculate the cart's overall total.
- The main function implements a user interaction loop, displaying a menu and reading console input to perform desired operations.
- User input is validated to ensure quantities and prices are valid positive numbers.
- The code is commented in Italian to facilitate understanding and maintenance.

Example Code: dart

import 'dart:io';

// Class representing a product in the cart
class Prodotto {
  String nome;
  double prezzoUnitario;
  int quantita;

  Prodotto({required this.nome, required this.prezzoUnitario, required this.quantita});

  // Calculates the total price for this product (unitPrice * quantity)
  double prezzoTotale() => prezzoUnitario * quantita;

  @override
  String toString() {
    return '$nome - Unit price: €${prezzoUnitario.toStringAsFixed(2)}, Quantity: $quantita, Total: €${prezzoTotale().toStringAsFixed(2)}';
  }
}

// Class that manages the shopping cart
class Carrello {
  final List<Prodotto> _prodotti = [];

  // Adds a product to the cart or updates the quantity if already present
  void aggiungiProdotto(Prodotto prodotto) {
    for (var p in _prodotti) {
      if (p.nome.toLowerCase() == prodotto.nome.toLowerCase()) {
        p.quantita += prodotto.quantita;
        print('Quantity updated for product "${p.nome}".');
        return;
      }
    }
    _prodotti.add(prodotto);
    print('Product "${prodotto.nome}" added to the cart.');
  }

  // Removes a product from the cart by name
  bool rimuoviProdotto(String nome) {
    return _prodotti.removeWhere((p) => p.nome.toLowerCase() == nome.toLowerCase()) > 0;
  }

  // Modifies the quantity of an existing product
  bool modificaQuantita(String nome, int nuovaQuantita) {
    for (var p in _prodotti) {
      if (p.nome.toLowerCase() == nome.toLowerCase()) {
        p.quantita = nuovaQuantita;
        return true;
      }
    }
    return false;
  }

  // Calculates the overall total of the cart
  double totale() {
    double somma = 0.0;
    for (var p in _prodotti) {
      somma += p.prezzoTotale();
    }
    return somma;
  }

  // Shows all products in the cart
  void mostraProdotti() {
    if (_prodotti.isEmpty) {
      print('The cart is empty.');
      return;
    }
    print('Products in the cart:');
    for (var p in _prodotti) {
      print('- ${p.toString()}');
    }
    print('Cart total: €${totale().toStringAsFixed(2)}');
  }
}

// Function to read a line from console with prompt
String leggiInput(String prompt) {
  stdout.write(prompt);
  return stdin.readLineSync() ?? '';
}

// Function to read a positive double from console
double leggiDoublePositivo(String prompt) {
  while (true) {
    String input = leggiInput(prompt);
    try {
      double valore = double.parse(input.replaceAll(',', '.'));
      if (valore > 0) {
        return valore;
      } else {
        print('Please enter a positive number.');
      }
    } catch (e) {
      print('Invalid input. Try again.');
    }
  }
}

// Function to read a positive int from console
int leggiIntPositivo(String prompt) {
  while (true) {
    String input = leggiInput(prompt);
    try {
      int valore = int.parse(input);
      if (valore > 0) {
        return valore;
      } else {
        print('Please enter a positive integer.');
      }
    } catch (e) {
      print('Invalid input. Try again.');
    }
  }
}

void main() {
  Carrello carrello = Carrello();
  bool uscita = false;

  print('Welcome to the Shopping Cart Simulator!');

  while (!uscita) {
    print('\nMenu:');
    print('1 - Add product');
    print('2 - Remove product');
    print('3 - Modify product quantity');
    print('4 - Show cart');
    print('5 - Exit');

    String scelta = leggiInput('Choose an option (1-5): ');

    switch (scelta) {
      case '1':
        String nome = leggiInput('Product name: ').trim();
        if (nome.isEmpty) {
          print('Product name cannot be empty.');
          break;
        }
        double prezzo = leggiDoublePositivo('Unit price (€): ');
        int quantita = leggiIntPositivo('Quantity: ');
        carrello.aggiungiProdotto(Prodotto(nome: nome, prezzoUnitario: prezzo, quantita: quantita));
        break;

      case '2':
        String nome = leggiInput('Name of product to remove: ').trim();
        if (carrello.rimuoviProdotto(nome)) {
          print('Product "$nome" successfully removed.');
        } else {
          print('Product "$nome" not found in the cart.');
        }
        break;

      case '3':
        String nome = leggiInput('Name of product to modify: ').trim();
        int nuovaQuantita = leggiIntPositivo('New quantity: ');
        if (carrello.modificaQuantita(nome, nuovaQuantita)) {
          print('Quantity updated for "$nome".');
        } else {
          print('Product "$nome" not found in the cart.');
        }
        break;

      case '4':
        carrello.mostraProdotti();
        break;

      case '5':
        uscita = true;
        print('Thank you for using the simulator. Goodbye!');
        break;

      default:
        print('Invalid option. Try again.');
    }
  }
}
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

Software: Dart SDK (version 2.12 or higher for null safety)

Software: No external dependencies required

Configuration: Run from terminal/console with command 'dart run filename.dart'

Software components:
  • Product class: represents a product with name, price, and quantity
  • Cart class: manages a list of products and operations on them
  • Main function: text user interface to interact with the cart

Similar Topics

Sum Calculator for Two Numbers in Console
Simple Dart program to read two integers from keyboard, calculate their sum, and display the result in console. Perfect for beginners learning I/O and arithmeti
Print Numbers from 1 to 1 in Console
Simple Dart program printing numbers 1 to 1 in console, ideal for beginners learning loops and console output in Dart programming.
Countdown Simulator with While Loop in Dart
Learn how to create a countdown simulator in Dart using a while loop and Timer.periodic for one-second intervals, ideal for DartPad or local use.
Guess the Number Simulator with Limited Attempts
A Dart console game simulating ’Guess the Number’ with limited attempts, hints, and input validation using Dart standard libraries.
Console To-Do List Simulator with Add and Remove
A Dart console To-Do list simulator allowing users to add, view, and remove tasks with simple input/output and dynamic list management.
Mini Rule Engine for Cart Discounts with Classes and Interfaces
Mini rule engine in Dart for cart discounts using classes and interfaces, enabling flexible, extendable discount rules in e-commerce applications.
Personal Expense Management Application with Categories and Monthly Console Reports
Dart console app for personal expense management with categories, monthly reports, JSON data persistence, and async file handling.
Queue Simulator for Service Desk with Average Time Statistics
Dart queue simulator for service desk managing customer arrivals, service, and real-time average waiting and service time statistics with console interface.