Tareas de ejercicio Aprende programación con ejercicios Visual Basic (VB.net)

Lección:

Matrices, Estructuras y Cadenas


Ejercicio:

Tareas de ejercicio 32


Objetivo:

Crea un programa en Visual Basic (VB.net) que puede almacenar hasta 2000 "tareas pendientes". Para cada tarea, debe conservar los siguientes datos:

• Fecha (un conjunto de 3 datos: día, mes y año)
• Descripción de la tarea
• Nivel de importancia (1 a 10)
• Categoría

El programa debe permitir al usuario las siguientes operaciones:

1 - Añadir una nueva tarea (la fecha debe "parecer correcta": día 1 al 31, mes 1 al 12, año entre 1000 y 3000).

2 - Mostrar las tareas entre dos fechas determinadas (día, mes y año). Si el usuario presiona Intro sin especificar la fecha, se tomará como "hoy". Debe mostrar el número de cada registro, la fecha (DD / MM / AAAA), descripción, categoría e importancia, todo en la misma línea, separado con guiones.

3 - Encuentre tareas que contengan un texto determinado (en descripción o categoría, no distingue entre mayúsculas y minúsculas). Mostrará número, fecha y descripción (solo 50 letras, en caso de que fuera más largo). Se debe notificar al usuario si no se encuentra ninguno.

4 - Actualizar un registro (te pedirá el número, mostrará el valor anterior de cada campo y el usuario podrá pulsar Intro para no modificar ninguno de los datos). Se debe advertir al usuario (pero no se le debe preguntar de nuevo) si ingresa un número de registro incorrecto. No es necesario validar ninguno de los campos.

5 - Eliminar algunos datos, entre dos posiciones indicadas por el usuario. Se debe advertir al usuario (pero no se le debe preguntar de nuevo) si ingresa algún número de registro incorrecto. Cada registro que se elimine debe mostrarse y se debe solicitar al usuario confirmación.

6 - Ordenar los datos alfabéticamente por fecha y (si dos fechas son iguales) por descripción.

7 - Buscar duplicados: Si dos registros tienen la misma descripción, ambos se mostrarán en pantalla.

P - Salir (finalizar la aplicación; como no almacenamos la información, se perderá).

(Sugerencia: puede conocer la fecha actual usando DateTime.Now.Day, DateTime.Now.Month y DateTime.Now.Year).


Código:

Imports System
Public Class exercis95
    Structure DateType
        Public year As UShort
        Public month As Byte
        Public day As Byte
    End Structure

    Structure TaskType
        Public date As DateType
        Public description As String
        Public level As Byte
        Public category As String
    End Structure

    Public Shared Sub Main()
        Dim capacity As Integer = 2000
        Dim tasks As TaskType() = New TaskType(capacity - 1) {}
        Dim [option] As Char
        Dim counter As Integer = 0
        Dim search, newValue As String
        Dim found As Boolean

        Do
            Console.WriteLine()
            Console.WriteLine("Tasks database")
            Console.WriteLine()
            Console.WriteLine("1- Add a new task.")
            Console.WriteLine("2- Show the tasks between two certain dates.")
            Console.WriteLine("3- Find tasks that contain a certain text.")
            Console.WriteLine("4- Update a record.")
            Console.WriteLine("5- Delete some data, between two positions indicated.")
            Console.WriteLine("6- Sort the data alphabetically by date.")
            Console.WriteLine("7- Find Duplicates.")
            Console.WriteLine("Q- Quit.")
            Console.WriteLine("Enter an option:")
            [option] = Convert.ToChar(Console.ReadLine().ToUpper())

            Select Case [option]
                Case "1"c

                    If counter < capacity Then
                        Console.Write("Enter the Description of the task: ")
                        tasks(counter).description = Console.ReadLine()
                        Console.Write("Enter the Level of the task (1-10): ")
                        tasks(counter).level = Convert.ToByte(Console.ReadLine())
                        Console.Write("Enter the Category of the task: ")
                        tasks(counter).category = Console.ReadLine()

                        Do
                            Console.Write("Enter the Day of the task (1 to 31): ")
                            tasks(counter).date.day = Convert.ToByte(Console.ReadLine())
                            If tasks(counter).date.day < 1 OrElse tasks(counter).date.day > 31 Then Console.WriteLine("Not a valid day!")
                        Loop While tasks(counter).date.day < 1 OrElse tasks(counter).date.day > 31

                        Do
                            Console.Write("Enter the Month of the task (1 to 12): ")
                            tasks(counter).date.month = Convert.ToByte(Console.ReadLine())
                            If tasks(counter).date.month < 1 OrElse tasks(counter).date.month > 12 Then Console.WriteLine("Not a valid month!")
                        Loop While tasks(counter).date.month < 1 OrElse tasks(counter).date.month > 12

                        Do
                            Console.Write("Enter the Year of the task: ")
                            tasks(counter).date.year = Convert.ToUInt16(Console.ReadLine())
                            If tasks(counter).date.year < 1000 OrElse tasks(counter).date.year > 3000 Then Console.WriteLine("Not a valid year!")
                        Loop While tasks(counter).date.year < 1000 OrElse tasks(counter).date.year > 3000

                        counter += 1
                    Else
                        Console.WriteLine("Database full.")
                    End If

                Case "2"c

                    If counter >= 1 Then
                        Dim startDay, startMonth As Byte
                        Dim startYear As UShort
                        Dim endDay, endMonth As Byte
                        Dim endYear As UShort
                        Console.WriteLine("Starting day: ")
                        Dim number As String = Console.ReadLine()

                        If number = "" Then
                            startDay = Convert.ToByte(DateTime.Now.Day)
                        Else
                            startDay = Convert.ToByte(number)
                        End If

                        Console.WriteLine("Starting month: ")
                        number = Console.ReadLine()

                        If number = "" Then
                            startMonth = Convert.ToByte(DateTime.Now.Month)
                        Else
                            startMonth = Convert.ToByte(number)
                        End If

                        Console.WriteLine("Starting year: ")
                        number = Console.ReadLine()

                        If number = "" Then
                            startYear = Convert.ToUInt16(DateTime.Now.Year)
                        Else
                            startYear = Convert.ToUInt16(number)
                        End If

                        Console.WriteLine("Final day: ")
                        number = Console.ReadLine()

                        If number = "" Then
                            endDay = Convert.ToByte(DateTime.Now.Day)
                        Else
                            endDay = Convert.ToByte(number)
                        End If

                        Console.WriteLine("Final month: ")
                        number = Console.ReadLine()

                        If number = "" Then
                            endMonth = Convert.ToByte(DateTime.Now.Month)
                        Else
                            endMonth = Convert.ToByte(number)
                        End If

                        Console.WriteLine("Final year: ")
                        number = Console.ReadLine()

                        If number = "" Then
                            endYear = Convert.ToUInt16(DateTime.Now.Year)
                        Else
                            endYear = Convert.ToUInt16(number)
                        End If

                        Dim startDate As String = "" & startYear & startMonth.ToString("00") & startDay.ToString("00")
                        Dim endDate As String = "" & endYear & endMonth.ToString("00") & endDay.ToString("00")

                        For i As Integer = 0 To counter - 1
                            Dim currentDate As String = "" & tasks(i).date.year & tasks(i).date.month.ToString("00") & tasks(i).date.day.ToString("00")

                            If currentDate.CompareTo(startDate) >= 0 AndAlso currentDate.CompareTo(endDate) <= 0 Then
                                Console.WriteLine("The number is {0}: {1}/{2}/" & "{3} - {4} - {5} - {6}.", i + 1, tasks(i).date.day, tasks(i).date.month, tasks(i).date.year, tasks(i).description, tasks(i).category, tasks(i).level)
                            End If
                        Next
                    Else
                        Console.WriteLine("Database empty.")
                    End If

                Case "3"c

                    If counter >= 1 Then
                        Console.Write("Enter the text to search: ")
                        search = Console.ReadLine()
                        found = False
                        Dim newValue5 As String

                        For i As Integer = 0 To counter - 1

                            If tasks(i).description.IndexOf(search) >= 0 OrElse tasks(i).category.IndexOf(search) >= 0 Then

                                If tasks(i).description.Length > 50 Then
                                    newValue5 = tasks(i).description.Substring(0, 50)
                                Else
                                    newValue5 = tasks(i).description
                                End If

                                found = True
                                Console.WriteLine("{0}: {1}/{2}/{3} - {4}", i + 1, tasks(i).date.day, tasks(i).date.month, tasks(i).date.year, newValue5)
                            End If
                        Next

                        If Not found Then Console.WriteLine("Not found.")
                    Else
                        Console.WriteLine("Database empty.")
                    End If

                Case "4"c

                    If counter >= 1 Then
                        Console.Write("Enter the number of the task to update: ")
                        Dim update As Integer = Convert.ToInt32(Console.ReadLine()) - 1

                        If (update >= 0) AndAlso (update < counter) Then
                            Console.Write("Description ({0}): ", tasks(update).description)
                            newValue = Console.ReadLine()
                            If newValue <> "" Then tasks(update).description = newValue
                            Console.WriteLine("Level ({0}): ", tasks(update).level)
                            newValue = Console.ReadLine()
                            If newValue <> "" Then tasks(update).level = Convert.ToByte(newValue)
                            Console.WriteLine("Category ({0}): ", tasks(update).category)
                            newValue = Console.ReadLine()
                            If newValue <> "" Then tasks(update).category = newValue
                            Console.WriteLine("Year ({0}): ", tasks(update).date.year)
                            newValue = Console.ReadLine()
                            If newValue <> "" Then tasks(update).date.year = Convert.ToUInt16(newValue)
                            Console.WriteLine("Month ({0}): ", tasks(update).date.month)
                            newValue = Console.ReadLine()
                            If newValue <> "" Then tasks(update).date.month = Convert.ToByte(newValue)
                            Console.WriteLine("Day ({0}): ", tasks(update).date.day)
                            newValue = Console.ReadLine()
                            If newValue <> "" Then tasks(update).date.day = Convert.ToByte(newValue)
                        Else
                            Console.WriteLine("Wrong number entered.")
                        End If
                    Else
                        Console.WriteLine("Database empty.")
                    End If

                Case "5"c

                    If counter >= 1 Then
                        Console.Write("Enter the first number of data to delete: ")
                        Dim delete As Integer = Convert.ToInt32(Console.ReadLine()) - 1
                        Console.Write("Enter the second number of data to delete: ")
                        Dim delete2 As Integer = Convert.ToInt32(Console.ReadLine()) - 1

                        For pos As Integer = delete To delete2

                            For i As Integer = delete To counter - 1
                                tasks(i) = tasks(i + 1)
                            Next

                            counter -= 1
                        Next
                    Else
                        Console.WriteLine("Database empty.")
                    End If

                Case "6"c

                    For i As Integer = 0 To counter - 1 - 1
                        Dim firstDate As String = "" & tasks(i).date.year & tasks(i).date.month.ToString("00") & tasks(i).date.day.ToString("00") & tasks(i).description

                        For j As Integer = i + 1 To counter - 1
                            Dim secondDate As String = "" & tasks(j).date.year & tasks(j).date.month.ToString("00") & tasks(j).date.day.ToString("00") & tasks(j).description

                            If firstDate.CompareTo(secondDate) > 0 Then
                                Dim aux As TaskType = tasks(i)
                                tasks(i) = tasks(j)
                                tasks(j) = aux
                            End If
                        Next
                    Next

                Case "7"c

                    For i As Integer = 0 To counter - 1 - 1

                        For j As Integer = i + 1 To counter - 1

                            If tasks(i).description = tasks(j).description Then
                                Console.WriteLine("{0} - {1}/{2}/{3}", tasks(i).description, tasks(i).date.day, tasks(i).date.month, tasks(i).date.year)
                                Console.WriteLine("{0} - {1}/{2}/{3}", tasks(j).description, tasks(j).date.day, tasks(j).date.month, tasks(j).date.year)
                            End If
                        Next
                    Next

                Case "Q"c
                    Console.WriteLine("Quitting...")
                Case Else
                    Console.WriteLine("You entered a wrong option. Please re-enter it.")
            End Select
        Loop While [option] <> "Q"c
    End Sub
End Class