Cuentas del hogar Aprende programación con ejercicios Visual Basic (VB.net)

Lección:

Matrices, Estructuras y Cadenas


Ejercicio:

Cuentas del hogar 54


Objetivo:

Cree un programa en Visual Basic (VB.net) que pueda almacenar hasta 10000 costos e ingresos, para crear un pequeño sistema de contabilidad nacional. Para cada gasto (o ingreso), se debe permitir guardar la siguiente información:

• Fecha (8 caracteres: formato AAAAMMDD)
• Descripción de los gastos o ingresos
• Categoría
• Monto (si es un ingreso positivo, negativo si es un gasto)

El programa debe permitir al usuario realizar las siguientes operaciones:

1 - Añadir un nuevo gasto (la fecha debe "verse bien": día 01 a 31 meses de 01 a 12 años entre 1000 y 3000). La descripción no debe estar vacía. No hace falta validar los otros datos.

2 - Mostrar todos los gastos de una determinada categoría (por ejemplo, "estudios") entre dos fechas determinadas (por ejemplo, entre "20110101" y "20111231"). Se muestra el número, la fecha (formato DD / MM / AAAA), la descripción, la categoría entre paréntesis y la cantidad a dos decimales, todo en la misma línea, separados por guiones. Al final de todos los datos, muestre la cantidad total de datos mostrados.

3 - Costos de búsqueda que contienen un determinado texto (en la descripción o categoría sin distinguir entre mayúsculas y minúsculas). Se muestra el número, la fecha y la descripción (la descripción se muestra en el sexto espacio en blanco truncado, si hay espacios seis o más).

4 - Modificar una pestaña (el número de pestaña lo pedirá al usuario, mostrará el valor anterior de cada campo y pulsará Intro para no poder modificar ninguno de los datos). Se debe avisar (pero no volver a ordenar) si el usuario introduce un número de tarjeta incorrecto. No hace falta validar ningún dato.

5 - Elimina algunos datos, del número que introduzcas. Se debe avisar (pero no volver a ordenar) si ingresa un número incorrecto. Debe mostrar que la tarjeta es clara y rápida antes de la eliminación.

6 - Ordenar los datos alfabéticamente, por fecha y (si coinciden) descripción.

7 - Normalizar descripciones: eliminar espacios finales, espacios y sitios espejo. Si una descripción es toda mayúscula, se convertirá a minúscula (excepto la primera letra, mantenida en mayúsculas).

T-End el uso de la aplicación (a medida que almacenamos la información, los datos se perderán).


Código:

Imports System
Public Class exercise96
    Structure accountData
        Public date As String
        Public description As String
        Public category As String
        Public amount As Double
    End Structure

    Public Shared Sub Main()
        Dim capacity As Integer = 10000
        Dim data As accountData() = New accountData(capacity - 1) {}
        Dim repeat As Boolean = True
        Dim [option] As String
        Dim amountOfData As Integer = 0

        Do
            Console.WriteLine()
            Console.WriteLine("Household accounts")
            Console.WriteLine()
            Console.WriteLine("1.- Add data.")
            Console.WriteLine("2.- View all data.")
            Console.WriteLine("3.- Search data.")
            Console.WriteLine("4.- Modify data.")
            Console.WriteLine("5.- Delete data.")
            Console.WriteLine("6.- Sort alphabetically")
            Console.WriteLine("7.- Fix spaces")
            Console.WriteLine("Q,T.-Quit.")
            Console.Write("Option: ")
            [option] = Console.ReadLine()

            Select Case [option]
                Case "1"

                    If amountOfData > capacity - 1 Then
                        Console.WriteLine("Database full!")
                    Else

                        Do
                            Console.Write("Enter date (YYYYMMDD): ")
                            data(amountOfData).date = Console.ReadLine()
                        Loop While data(amountOfData).date.Length = 0

                        Do
                            Console.Write("Enter Description: ")
                            data(amountOfData).description = Console.ReadLine()
                            If data(amountOfData).description.Length = 0 Then Console.Write("Cannot be empty")
                        Loop While data(amountOfData).description.Length = 0

                        Console.Write("Enter category: ")
                        data(amountOfData).category = Console.ReadLine()
                        Console.Write("Enter the amount: ")
                        data(amountOfData).amount = Convert.ToDouble(Console.ReadLine())
                        amountOfData += 1
                    End If

                Case "2"

                    If amountOfData = 0 Then
                        Console.WriteLine("No data!")
                    Else
                        Console.Write("Enter the category: ")
                        Dim categ As String = Console.ReadLine()
                        Console.Write("Enter the start date (YYYYMMDD): ")
                        Dim startDate As String = Console.ReadLine()
                        Console.Write("Enter the end date (YYYYMMDD): ")
                        Dim endDate As String = Console.ReadLine()

                        For i As Integer = 0 To amountOfData - 1

                            If (data(i).category = categ) AndAlso (data(i).date.CompareTo(startDate) >= 0) AndAlso (data(i).date.CompareTo(endDate) <= 0) Then
                                Console.WriteLine("{0} - {1}/{2}/{3} - {4} -({5}) - {6}", i + 1, data(i).date.Substring(6, 2), data(i).date.Substring(4, 2), data(i).date.Substring(0, 4), data(i).description, data(i).category, data(i).amount.ToString("N2"))
                            End If
                        Next
                    End If

                Case "3"
                    Console.Write("Enter part of the description or category: ")
                    Dim search As String = Console.ReadLine().ToUpper()
                    Dim found As Boolean = False

                    For i As Integer = 0 To amountOfData - 1

                        If data(i).description.ToUpper().Contains(search) OrElse data(i).category.ToUpper().Contains(search) Then
                            Console.WriteLine("{0}: {1} - {2}", i + 1, data(i).date, data(i).description)
                            found = True
                        End If
                    Next

                    If Not found Then Console.WriteLine("Not found!")
                Case "4"
                    Console.Write("Enter the record number: ")
                    Dim recNumber As Integer = Convert.ToInt32(Console.ReadLine()) - 1

                    If (recNumber > amountOfData) OrElse (recNumber < 0) Then
                        Console.Write("Out of range!")
                    Else
                        Console.Write("Date (was {0}; hit ENTER to leave as is): ", data(recNumber).date)
                        Dim newText As String = Console.ReadLine()
                        If newText <> "" Then data(recNumber).date = newText
                        Console.Write("Description (was {0}; hit ENTER to leave as is): ", data(recNumber).description)
                        newText = Console.ReadLine()
                        If newText <> "" Then data(recNumber).description = newText
                        Console.Write("Category (was {0}; hit ENTER to leave as is): ", data(recNumber).category)
                        newText = Console.ReadLine()
                        If newText <> "" Then data(recNumber).category = newText
                        Console.Write("Amount (was {0}; hit ENTER to leave as is): ", data(recNumber).amount)
                        newText = Console.ReadLine()
                        If newText <> "" Then data(recNumber).amount = Convert.ToDouble(newText)
                    End If

                Case "5"
                    Dim position As Integer = 0
                    Console.Write("Enter the position number to delete: ")
                    position = Convert.ToInt32(Console.ReadLine()) - 1

                    If position > amountOfData Then
                        Console.WriteLine("Error: out of range")
                    Else

                        For i As Integer = position To amountOfData - 1
                            data(i) = data(i + 1)
                        Next

                        amountOfData -= 1
                    End If

                Case "6"
                    Dim aux As accountData

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

                        For j As Integer = i + 1 To amountOfData - 1
                            Dim data1 As String = data(i).date & data(i).description
                            Dim data2 As String = data(j).date & data(j).description

                            If data1.CompareTo(data2) > 0 Then
                                aux = data(i)
                                data(i) = data(j)
                                data(j) = aux
                            End If
                        Next
                    Next

                    Console.WriteLine("Sorted.")
                Case "7"

                    For i As Integer = 0 To amountOfData - 1
                        data(i).description = data(i).description.Trim()

                        While data(i).description.Contains("  ")
                            data(i).description = data(i).description.Replace("  ", " ")
                        End While

                        If data(i).description = data(i).description.ToUpper() Then data(i).description = data(i).description.Substring(0, 1).ToUpper() & data(i).description.Substring(1).ToLower()
                    Next

                Case "T", "t", "Q", "q"
                    repeat = False
                Case Else
                    Console.WriteLine("Wrong option!")
            End Select
        Loop While repeat <> False

        Console.WriteLine("Bye!")
    End Sub
End Class