Catálogo + Menú - Ejercicio de Programacion C# Sharp

En este ejercicio de C#, se debe mejorar el programa del catálogo para que el método Main muestre un menú que permita ingresar nuevos datos de cualquier tipo, así como mostrar todos los datos almacenados. El menú debe ofrecer opciones para añadir nuevos elementos al catálogo, como archivos de música, películas y programas de computadora, y para mostrar la información almacenada en el sistema.

El programa debe ser capaz de agregar la información de cada tipo de objeto (nombre, código, categoría, tamaño, y los atributos específicos para música y películas) y permitir al usuario visualizar todos los elementos guardados en el catálogo. Este ejercicio es una excelente oportunidad para mejorar las habilidades en C# relacionadas con la interacción con el usuario, el manejo de menús, y la manipulación de colecciones de objetos, además de practicar la organización y visualización de datos.

 Categoría

POO Más sobre Clases

 Ejercicio

Catálogo + Menú

 Objectivo

Mejorar el programa Catálogo, de forma que "Principal" muestre un menú que permita introducir nuevos datos de cualquier tipo, así como visualizar todos los datos almacenados.

 Ejemplo Ejercicio C#

 Copiar Código C#
// Importing the System namespace to handle basic functionalities and console output
using System;
using System.Collections.Generic;

// Defining the base class 'CatalogItem' to represent an item in the catalog
public class CatalogItem
{
    public string Name { get; set; }     // Name of the catalog item
    public string Code { get; set; }     // Code to identify the catalog item
    public string Category { get; set; } // Category of the catalog item (e.g., music, film, program)
    public double Size { get; set; }     // Size of the catalog item (e.g., size of a file)

    // Constructor to initialize the catalog item with necessary details
    public CatalogItem(string name, string code, string category, double size)
    {
        Name = name;         // Set the name of the catalog item
        Code = code;         // Set the code for the catalog item
        Category = category; // Set the category of the catalog item
        Size = size;         // Set the size of the catalog item
    }

    // Method to display information about the catalog item
    public virtual void Display()
    {
        Console.WriteLine($"Name: {Name}, Code: {Code}, Category: {Category}, Size: {Size}MB");
    }
}

// Defining the MusicFile class that extends CatalogItem, with additional properties for music
public class MusicFile : CatalogItem
{
    public string Singer { get; set; }  // Singer of the music file
    public double Length { get; set; }  // Length of the music file in seconds

    // Constructor to initialize a music file with additional properties
    public MusicFile(string name, string code, string category, double size, string singer, double length)
        : base(name, code, category, size)
    {
        Singer = singer;   // Set the singer of the music file
        Length = length;   // Set the length of the music file in seconds
    }

    // Overriding the Display method to show music-specific information
    public override void Display()
    {
        base.Display(); // Call the base class method to display common information
        Console.WriteLine($"Singer: {Singer}, Length: {Length} seconds");
    }
}

// Defining the Film class that extends CatalogItem, with additional properties for films
public class Film : CatalogItem
{
    public string Director { get; set; }   // Director of the film
    public string MainActor { get; set; }   // Main actor in the film
    public string MainActress { get; set; } // Main actress in the film

    // Constructor to initialize a film with additional properties
    public Film(string name, string code, string category, double size, string director, string mainActor, string mainActress)
        : base(name, code, category, size)
    {
        Director = director;       // Set the director of the film
        MainActor = mainActor;     // Set the main actor of the film
        MainActress = mainActress; // Set the main actress of the film
    }

    // Overriding the Display method to show film-specific information
    public override void Display()
    {
        base.Display(); // Call the base class method to display common information
        Console.WriteLine($"Director: {Director}, Main Actor: {MainActor}, Main Actress: {MainActress}");
    }
}

// Defining the ComputerProgram class that extends CatalogItem, with additional properties for computer programs
public class ComputerProgram : CatalogItem
{
    // Constructor to initialize a computer program with properties
    public ComputerProgram(string name, string code, string category, double size)
        : base(name, code, category, size)
    {
    }

    // Overriding the Display method to show program-specific information
    public override void Display()
    {
        base.Display(); // Call the base class method to display common information
    }
}

// Main program to implement the catalog system and the menu
public class Program
{
    // List to store different catalog items (music, films, programs)
    private static List catalogItems = new List();

    public static void Main()
    {
        bool keepRunning = true; // Flag to keep the program running until the user decides to exit
        while (keepRunning)
        {
            // Displaying the menu options to the user
            Console.WriteLine("Catalog Menu:");
            Console.WriteLine("1. Add a new music file");
            Console.WriteLine("2. Add a new film");
            Console.WriteLine("3. Add a new computer program");
            Console.WriteLine("4. Display all catalog items");
            Console.WriteLine("5. Exit");
            Console.Write("Select an option (1-5): ");
            
            // Reading the user's selection
            int option = Convert.ToInt32(Console.ReadLine());

            // Handling the menu options
            switch (option)
            {
                case 1:
                    AddMusicFile(); // Call the method to add a music file
                    break;
                case 2:
                    AddFilm(); // Call the method to add a film
                    break;
                case 3:
                    AddComputerProgram(); // Call the method to add a computer program
                    break;
                case 4:
                    DisplayCatalog(); // Call the method to display all catalog items
                    break;
                case 5:
                    keepRunning = false; // Set the flag to false to exit the program
                    break;
                default:
                    Console.WriteLine("Invalid option. Please try again.");
                    break;
            }
        }
    }

    // Method to add a new music file to the catalog
    private static void AddMusicFile()
    {
        // Prompting the user for music file details
        Console.Write("Enter the name of the music file: ");
        string name = Console.ReadLine();
        Console.Write("Enter the code of the music file: ");
        string code = Console.ReadLine();
        Console.Write("Enter the category of the music file: ");
        string category = Console.ReadLine();
        Console.Write("Enter the size of the music file (MB): ");
        double size = Convert.ToDouble(Console.ReadLine());
        Console.Write("Enter the singer: ");
        string singer = Console.ReadLine();
        Console.Write("Enter the length of the music file (seconds): ");
        double length = Convert.ToDouble(Console.ReadLine());

        // Creating a new MusicFile object and adding it to the catalog
        MusicFile musicFile = new MusicFile(name, code, category, size, singer, length);
        catalogItems.Add(musicFile);
    }

    // Method to add a new film to the catalog
    private static void AddFilm()
    {
        // Prompting the user for film details
        Console.Write("Enter the name of the film: ");
        string name = Console.ReadLine();
        Console.Write("Enter the code of the film: ");
        string code = Console.ReadLine();
        Console.Write("Enter the category of the film: ");
        string category = Console.ReadLine();
        Console.Write("Enter the size of the film (MB): ");
        double size = Convert.ToDouble(Console.ReadLine());
        Console.Write("Enter the director of the film: ");
        string director = Console.ReadLine();
        Console.Write("Enter the main actor of the film: ");
        string mainActor = Console.ReadLine();
        Console.Write("Enter the main actress of the film: ");
        string mainActress = Console.ReadLine();

        // Creating a new Film object and adding it to the catalog
        Film film = new Film(name, code, category, size, director, mainActor, mainActress);
        catalogItems.Add(film);
    }

    // Method to add a new computer program to the catalog
    private static void AddComputerProgram()
    {
        // Prompting the user for computer program details
        Console.Write("Enter the name of the computer program: ");
        string name = Console.ReadLine();
        Console.Write("Enter the code of the computer program: ");
        string code = Console.ReadLine();
        Console.Write("Enter the category of the program: ");
        string category = Console.ReadLine();
        Console.Write("Enter the size of the program (MB): ");
        double size = Convert.ToDouble(Console.ReadLine());

        // Creating a new ComputerProgram object and adding it to the catalog
        ComputerProgram program = new ComputerProgram(name, code, category, size);
        catalogItems.Add(program);
    }

    // Method to display all catalog items (music files, films, programs)
    private static void DisplayCatalog()
    {
        // Checking if the catalog has any items
        if (catalogItems.Count == 0)
        {
            Console.WriteLine("No items in the catalog.");
        }
        else
        {
            // Displaying each catalog item
            Console.WriteLine("\nCatalog Items:");
            foreach (var item in catalogItems)
            {
                item.Display();  // Calling the Display method of each catalog item
                Console.WriteLine(); // Adding a blank line for readability
            }
        }

        // Waiting for the user to press a key before returning to the menu
        Console.WriteLine("Press any key to return to the menu.");
        Console.ReadKey();
    }
}

 Salida

Catalog Menu:
1. Add a new music file
2. Add a new film
3. Add a new computer program
4. Display all catalog items
5. Exit
Select an option (1-5): 1
Enter the name of the music file: Roxette
Enter the code of the music file: 1245
Enter the category of the music file: Pop
Enter the size of the music file (MB): 125
Enter the singer: Roxette
Enter the length of the music file (seconds): 1254
Catalog Menu:
1. Add a new music file
2. Add a new film
3. Add a new computer program
4. Display all catalog items
5. Exit
Select an option (1-5): 4

Catalog Items:
Name: Roxette, Code: 1245, Category: Pop, Size: 125MB
Singer: Roxette, Length: 1254 seconds

Press any key to return to the menu.

 Comparte este Ejercicio C# Sharp

 Más Ejercicios de Programacion C# Sharp de POO Más sobre Clases

¡Explora nuestro conjunto de ejercicios de programación C# Sharp! Estos ejercicios, diseñados específicamente para principiantes, te ayudarán a desarrollar una sólida comprensión de los conceptos básicos de C#. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte de manera gradual a medida que adquieres confianza en la codificación en C#.

  •  Matriz de objetos: tabla

    En este ejercicio, debes crear una clase llamada "Table". Esta clase debe tener un constructor que reciba el ancho y alto de la mesa. La clase...

  •  House

    En este ejercicio, debes crear una clase llamada "House" que tendrá un atributo llamado "area". La clase debe tener un constructor que permita asignar un valor...

  •  Tabla + coffetable + array

    En este ejercicio, debes crear un proyecto llamado "Tables2", basado en el proyecto "Tables". En este nuevo proyecto, debes crear una clase llamada "CoffeeTable" que ...

  •  Encriptador

    En este ejercicio, debes crear una clase llamada "Encrypter" para encriptar y desencriptar texto. La clase tendrá un método "Encrypt", que...

  •  Números complejos

    En este ejercicio de C#, se aborda el concepto de números complejos, que se componen de dos partes: la parte real y la parte imaginaria. En una expresión como a+bi (p...

  •  tabla + coffetable + leg

    En este ejercicio de C#, se extiende el ejemplo de las mesas y las mesas de café para agregar una clase llamada "Leg" (Pata). Esta clase debe tener un método denomina...