Ejercicio
Base de datos de libros
Objetivo
Cree una pequeña base de datos, que se utilizará para almacenar datos sobre libros. Para un determinado libro, queremos conservar la siguiente información:
Título
Autor
El programa debe ser capaz de almacenar 1000 libros, y el usuario podrá:
Agregar datos para un libro
Mostrar todos los libros introducidos (solo título y autor, en la misma línea)
Buscar el libro (s) con un título determinado
Eliminar un libro en una posición conocida (por ejemplo, el libro número 6)
Salir del programa
Sugerencia: para eliminar un elemento de una matriz, debe mover hacia atrás cada elemento que se colocó después de él y disminuir el contador.
Código de Ejemplo
using System;
struct Book
{
public string title;
public string author;
}
class Program
{
static void Main()
{
Book[] books = new Book[1000];
int bookCount = 0;
bool exit = false;
while (!exit)
{
Console.WriteLine("\nMenu:");
Console.WriteLine("1. Add data for one book");
Console.WriteLine("2. Display all entered books");
Console.WriteLine("3. Search for a book by title");
Console.WriteLine("4. Delete a book by position");
Console.WriteLine("5. Exit");
Console.Write("Choose an option (1-5): ");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
if (bookCount < books.Length)
{
Console.WriteLine("\nEnter data for Book " + (bookCount + 1) + ":");
Console.Write("Enter book title: ");
books[bookCount].title = Console.ReadLine();
Console.Write("Enter book author: ");
books[bookCount].author = Console.ReadLine();
bookCount++;
}
else
{
Console.WriteLine("Maximum number of books reached.");
}
break;
case "2":
if (bookCount > 0)
{
Console.WriteLine("\nEntered Books:");
for (int i = 0; i < bookCount; i++)
{
Console.WriteLine($"{i + 1}. Title: {books[i].title}, Author: {books[i].author}");
}
}
else
{
Console.WriteLine("No books entered yet.");
}
break;
case "3":
Console.Write("\nEnter the title of the book to search: ");
string searchTitle = Console.ReadLine();
bool found = false;
Console.WriteLine("\nSearch Results:");
for (int i = 0; i < bookCount; i++)
{
if (books[i].title.Equals(searchTitle, StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine($"{i + 1}. Title: {books[i].title}, Author: {books[i].author}");
found = true;
}
}
if (!found)
{
Console.WriteLine("No book found with that title.");
}
break;
case "4":
Console.Write("\nEnter the book number to delete: ");
int deleteIndex;
if (int.TryParse(Console.ReadLine(), out deleteIndex) && deleteIndex > 0 && deleteIndex <= bookCount)
{
for (int i = deleteIndex - 1; i < bookCount - 1; i++)
{
books[i] = books[i + 1];
}
bookCount--;
Console.WriteLine($"Book number {deleteIndex} has been deleted.");
}
else
{
Console.WriteLine("Invalid book number.");
}
break;
case "5":
exit = true;
Console.WriteLine("Exiting the program.");
break;
default:
Console.WriteLine("Invalid choice, please select a valid option.");
break;
}
}
}
}