Administración De Registros De Programas Informáticos En C#

En este programa de C#, crearemos un sistema para almacenar y gestionar hasta 1000 registros de programas informáticos. Cada programa tendrá los siguientes atributos: Nombre, Categoría, Descripción y Versión. El programa permitirá al usuario añadir, ver, actualizar, eliminar, ordenar y corregir espacios redundantes en los datos. Este ejercicio implica la validación de la entrada, la gestión del almacenamiento de datos y la interacción del usuario mediante una interfaz de línea de comandos. Demuestra el trabajo con estructuras, matrices y la manipulación de cadenas en C#.



Grupo

Matrices, estructuras y cadenas de C#

Objectivo

1. Implemente una estructura para almacenar la información de cada programa, incluyendo nombre, categoría, descripción y versión.
2. Cree un array de estructuras para almacenar hasta 1000 registros.
3. Implemente operaciones para agregar, mostrar, actualizar, eliminar, ordenar y corregir espacios redundantes en los registros.
4. Valide la entrada, garantizando que los formatos y límites de datos sean correctos.
5. Proporcione comentarios claros al usuario y gestione errores como números de programa no válidos.

Escriba un programa en C# que pueda almacenar hasta 1000 registros de programas informáticos. Para cada programa, debe mantener los siguientes datos: Nombre, Categoría, Descripción, Versión (es un conjunto de 3 datos: número de versión -texto-, mes de lanzamiento -byte- y año de lanzamiento -unsigned short-).

Ejemplo de ejercicio en C#

 Copiar código C#
using System;

class Program
{
    // Define the struct to hold information about a program
    struct ProgramRecord
    {
        public string Name; // Name of the program
        public string Category; // Category of the program
        public string Description; // Description of the program
        public string VersionNumber; // Version number of the program
        public byte LaunchMonth; // Launch month of the program
        public ushort LaunchYear; // Launch year of the program
    }

    static void Main()
    {
        ProgramRecord[] programs = new ProgramRecord[1000]; // Array to store up to 1000 programs
        int programCount = 0; // Counter to track the number of programs

        while (true)
        {
            Console.Clear(); // Clear the console screen
            // Display menu options to the user
            Console.WriteLine("1 - Add New Program");
            Console.WriteLine("2 - Show All Programs");
            Console.WriteLine("3 - View Program Data");
            Console.WriteLine("4 - Update Program Record");
            Console.WriteLine("5 - Delete Program Record");
            Console.WriteLine("6 - Sort Programs Alphabetically");
            Console.WriteLine("7 - Fix Redundant Spaces in Names");
            Console.WriteLine("X - Exit");
            Console.Write("Choose an option: ");
            string choice = Console.ReadLine(); // Get user choice

            if (choice == "1") // Add new program
            {
                if (programCount >= 1000) // Check if the database is full
                {
                    Console.WriteLine("Cannot add more programs. The database is full.");
                    Console.ReadKey();
                    continue;
                }

                // Getting user input for a new program
                ProgramRecord newProgram;
                Console.Write("Enter Program Name: ");
                newProgram.Name = Console.ReadLine().Trim(); // Get the name and trim whitespace

                // Validate name is not empty
                while (string.IsNullOrEmpty(newProgram.Name))
                {
                    Console.Write("Name cannot be empty. Enter Program Name: ");
                    newProgram.Name = Console.ReadLine().Trim(); // Re-prompt for a valid name
                }

                Console.Write("Enter Program Category (Max 30 characters): ");
                newProgram.Category = Console.ReadLine().Trim(); // Get category and trim whitespace
                // Validate category length
                while (newProgram.Category.Length > 30)
                {
                    Console.Write("Category too long. Enter Program Category (Max 30 characters): ");
                    newProgram.Category = Console.ReadLine().Trim(); // Re-prompt for valid category
                }

                Console.Write("Enter Program Description (Max 100 characters): ");
                newProgram.Description = Console.ReadLine().Length > 100
                    ? Console.ReadLine().Substring(0, 100) // Limit description length to 100 characters
                    : Console.ReadLine().Trim();

                Console.Write("Enter Program Version Number: ");
                newProgram.VersionNumber = Console.ReadLine(); // Get version number

                Console.Write("Enter Program Launch Month (1-12): ");
                newProgram.LaunchMonth = byte.Parse(Console.ReadLine()); // Get launch month

                Console.Write("Enter Program Launch Year: ");
                newProgram.LaunchYear = ushort.Parse(Console.ReadLine()); // Get launch year

                programs[programCount] = newProgram; // Add the new program to the array
                programCount++; // Increment the program count

                Console.WriteLine("Program added successfully!");
                Console.ReadKey();
            }
            else if (choice == "2") // Show all programs
            {
                if (programCount == 0) // Check if there are no programs
                {
                    Console.WriteLine("No programs available.");
                }
                else
                {
                    // Display all program names
                    for (int i = 0; i < programCount; i++)
                    {
                        Console.WriteLine(programs[i].Name);
                    }
                }
                Console.ReadKey();
            }
            else if (choice == "3") // View program data
            {
                Console.Write("Enter part of program name, category or description: ");
                string searchText = Console.ReadLine(); // Get search input
                bool found = false; // Flag to check if any program matches the search text

                for (int i = 0; i < programCount; i++)
                {
                    // Check if the program name, category, or description contains the search text
                    if (programs[i].Name.Contains(searchText) || 
                        programs[i].Category.Contains(searchText) || 
                        programs[i].Description.Contains(searchText))
                    {
                        // Display the program details
                        Console.WriteLine($"Program {i + 1}:");
                        Console.WriteLine($"Name: {programs[i].Name}");
                        Console.WriteLine($"Category: {programs[i].Category}");
                        Console.WriteLine($"Description: {programs[i].Description}");
                        Console.WriteLine($"Version: {programs[i].VersionNumber} | Launch Month: {programs[i].LaunchMonth} | Launch Year: {programs[i].LaunchYear}");
                        Console.WriteLine();
                        found = true;
                    }
                }

                if (!found) // If no matching programs were found
                {
                    Console.WriteLine("No matching programs found.");
                }

                Console.ReadKey();
            }
            else if (choice == "4") // Update program record
            {
                Console.Write("Enter program number to update: ");
                int programNumber = int.Parse(Console.ReadLine()) - 1; // Get program index to update

                if (programNumber >= 0 && programNumber < programCount) // Check if the program number is valid
                {
                    // Display the current program data
                    Console.WriteLine("Current Program Data:");
                    Console.WriteLine($"Name: {programs[programNumber].Name}");
                    Console.WriteLine($"Category: {programs[programNumber].Category}");
                    Console.WriteLine($"Description: {programs[programNumber].Description}");
                    Console.WriteLine($"Version: {programs[programNumber].VersionNumber}");
                    Console.WriteLine($"Launch Month: {programs[programNumber].LaunchMonth}");
                    Console.WriteLine($"Launch Year: {programs[programNumber].LaunchYear}");

                    // Prompt for new values, allowing the user to keep current values if left blank
                    Console.Write("Enter new name (leave blank to keep current): ");
                    string newName = Console.ReadLine();
                    if (!string.IsNullOrEmpty(newName)) programs[programNumber].Name = newName;

                    Console.Write("Enter new category (leave blank to keep current): ");
                    string newCategory = Console.ReadLine();
                    if (!string.IsNullOrEmpty(newCategory)) programs[programNumber].Category = newCategory;

                    Console.Write("Enter new description (leave blank to keep current): ");
                    string newDescription = Console.ReadLine();
                    if (!string.IsNullOrEmpty(newDescription)) programs[programNumber].Description = newDescription;

                    Console.Write("Enter new version number (leave blank to keep current): ");
                    string newVersion = Console.ReadLine();
                    if (!string.IsNullOrEmpty(newVersion)) programs[programNumber].VersionNumber = newVersion;

                    Console.Write("Enter new launch month (leave blank to keep current): ");
                    string newLaunchMonth = Console.ReadLine();
                    if (!string.IsNullOrEmpty(newLaunchMonth)) programs[programNumber].LaunchMonth = byte.Parse(newLaunchMonth);

                    Console.Write("Enter new launch year (leave blank to keep current): ");
                    string newLaunchYear = Console.ReadLine();
                    if (!string.IsNullOrEmpty(newLaunchYear)) programs[programNumber].LaunchYear = ushort.Parse(newLaunchYear);

                    Console.WriteLine("Program updated.");
                }
                else
                {
                    Console.WriteLine("Invalid program number.");
                }

                Console.ReadKey();
            }
            else if (choice == "5") // Delete program record
            {
                Console.Write("Enter program number to delete: ");
                int deleteIndex = int.Parse(Console.ReadLine()) - 1; // Get program index to delete

                if (deleteIndex >= 0 && deleteIndex < programCount) // Check if the program number is valid
                {
                    // Shift all programs after the deleted one to fill the gap
                    for (int i = deleteIndex; i < programCount - 1; i++)
                    {
                        programs[i] = programs[i + 1];
                    }
                    programCount--; // Decrease the program count
                    Console.WriteLine("Program deleted.");
                }
                else
                {
                    Console.WriteLine("Invalid program number.");
                }

                Console.ReadKey();
            }
            else if (choice == "6") // Sort programs by name
            {
                Array.Sort(programs, 0, programCount, Comparer.Create((x, y) => x.Name.CompareTo(y.Name)));
                Console.WriteLine("Programs sorted.");
                Console.ReadKey();
            }
            else if (choice == "7") // Fix redundant spaces in names
            {
                // Replace multiple spaces with a single space in program names
                for (int i = 0; i < programCount; i++)
                {
                    programs[i].Name = System.Text.RegularExpressions.Regex.Replace(programs[i].Name, @"\s+", " ");
                }
                Console.WriteLine("Redundant spaces fixed.");
                Console.ReadKey();
            }
            else if (choice.ToUpper() == "X") // Exit the application
            {
                break; // Exit the loop and end the program
            }
        }
    }
}

 Output

1 - Add New Program
2 - Show All Programs
3 - View Program Data
4 - Update Program Record
5 - Delete Program Record
6 - Sort Programs Alphabetically
7 - Fix Redundant Spaces in Names
X - Exit
Choose an option: 1
Enter Program Name: Example Program
Enter Program Category (Max 30 characters): Productivity
Enter Program Description (Max 100 characters): This is a description of the example program.
Enter Program Version Number: 1.0
Enter Program Launch Month (1-12): 12
Enter Program Launch

Comparte este ejercicio de C#

Practica más ejercicios C# de Matrices, estructuras y cadenas de C#

¡Explora nuestro conjunto de ejercicios de práctica de C#! Diseñados específicamente para principiantes, estos ejercicios te ayudarán a desarrollar una sólida comprensión de los fundamentos de C#. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte gradualmente a medida que adquieres confianza en la programación en C#..