Catálogo + Menú Ejercicio C# - Curso de Programación C# (C Sharp)

 Ejercicio

Catálogo + Menú

 Objetivo

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.

 Código de Ejemplo

// 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();
    }
}

Más ejercicios C# Sharp de POO Más sobre Clases

 Matriz de objetos: tabla
Cree una clase denominada "Table". Debe tener un constructor, indicando el ancho y alto de la placa. Tendrá un método "ShowData" que escribirá en la p...
 House
Cree una clase "House", con un atributo "area", un constructor que establezca su valor y un método "ShowData" para mostrar "Soy una casa, mi área es d...
 Tabla + coffetable + array
Cree un proyecto denominado "Tablas2", basado en el proyecto "Tablas". En él, cree una clase "CoffeeTable" que herede de "Table". Su método "ShowDa...
 Encriptador
Cree una clase "Encrypter" para cifrar y descifrar texto. Tendrá un método "Encrypt", que recibirá una cadena y devolverá otra cadena. Será un méto...
 Números complejos
Un número complejo tiene dos partes: la parte real y la parte imaginaria. En un número como a+bi (2-3i, por ejemplo) la parte real sería "a" (2) y la ...
 tabla + coffetable + leg
Amplíe el ejemplo de las tablas y las mesas de centro, para agregar una clase "Leg" con un método "ShowData", que escribirá "I am a leg" y luego mostr...
 Catálogo
Cree el diagrama de clases y, a continuación, con Visual Studio, un proyecto y las clases correspondientes para una utilidad de catálogo: Podrá alm...
 Número aleatorio
Cree una clase RandomNumber, con tres métodos estáticos: - GetFloat devolverá un número entre 0 y 1 utilizando el siguiente algoritmo: semilla =...
 Texto a HTML
Crear una clase "TextToHTML", que debe ser capaz de convertir varios textos introducidos por el usuario en una secuencia HTML, como esta: Hola Soy...
 Clase ScreenText
Cree una clase ScreenText, para mostrar un texto determinado en coordenadas de pantalla especificadas. Debe tener un constructor que recibirá X, Y y l...
 Clase ComplexNumber mejorada
Mejore la clase "ComplexNumber", para que sobrecargue los operadores + y - para sumar y restar números....
 Punto 3D
Cree una clase "Point3D", para representar un punto en el espacio 3D, con coordenadas X, Y y Z. Debe contener los siguientes métodos: MoveTo, que c...

Juan A. Ripoll - Tutoriales y Cursos de Programacion© 2025 Todos los derechos reservados.  Condiciones legales.