Ejercicio
Tabla + SetOfTables + archivos
Objetivo
Ampliar el ejercicio del 16 de abril (tablas + array + archivos), de manera que contenga tres clases: Table, SetOfTables y un programa de prueba. SetOfTables debe contener la matriz de tablas y dos métodos para volcar (todos) los datos de la matriz en un archivo binario y restaurar los datos del archivo.
Código
Imports System
Imports System.Collections
Imports System.IO
Namespace Tables
Class SetOfTables
Private size As Integer
Private data As ArrayList
Private random As Random
Public Sub New(ByVal newSize As Integer)
size = newSize
data = New ArrayList()
random = New Random()
End Sub
Public Sub New()
Me.New(10)
End Sub
Public Sub CreateAtRandom()
data = New ArrayList()
For i As Integer = 0 To size - 1
data.Add(New Table(random.[Next](50, 201)))
random.[Next](50, 201)
Next
End Sub
Public Sub ShowData()
For Each t As Table In data
t.ShowData()
Next
Console.WriteLine()
End Sub
Public Sub Save(ByVal name As String)
Dim outputFile As BinaryWriter = New BinaryWriter(File.Open(name, FileMode.Create))
outputFile.Write(CInt(size))
For Each t As Table In data
outputFile.Write(t.GetHeight())
outputFile.Write(t.GetWidth())
Next
outputFile.Close()
End Sub
Public Sub Load(ByVal name As String)
Dim inputFile As BinaryReader = New BinaryReader(File.Open(name, FileMode.Open))
Dim size As Integer = inputFile.ReadInt32()
data = New ArrayList()
For i As Integer = 0 To size - 1
Dim height As Integer = inputFile.ReadInt32()
Dim width As Integer = inputFile.ReadInt32()
data.Add(New Table(width, height))
Next
inputFile.Close()
End Sub
End Class
End Namespace
Namespace Tables
Class Table
Protected width, height As Integer
Public Sub New(ByVal tableWidth As Integer, ByVal tableHeight As Integer)
width = tableWidth
height = tableHeight
End Sub
Public Function GetHeight() As Integer
Return height
End Function
Public Function GetWidth() As Integer
Return width
End Function
Public Sub ShowData()
Console.WriteLine("Width: {0}, Height: {1}", width, height)
End Sub
Public Sub Save(ByVal name As String)
Dim outputFile As BinaryWriter = New BinaryWriter(File.Open(name, FileMode.Create))
outputFile.Write(height)
outputFile.Write(width)
outputFile.Close()
End Sub
Public Sub Load(ByVal name As String)
Dim inputFile As BinaryReader = New BinaryReader(File.Open(name, FileMode.Open))
height = inputFile.ReadInt32()
width = inputFile.ReadInt32()
inputFile.Close()
End Sub
End Class
End Namespace
Namespace Tables
Class TestTable
Private Shared Sub Main(ByVal args As String())
Dim s As SetOfTables = New SetOfTables(5)
s.CreateAtRandom()
s.ShowData()
s.Save("tables.dat")
s.CreateAtRandom()
s.ShowData()
s.Load("tables.dat")
s.ShowData()
Console.ReadLine()
End Sub
End Class
End Namespace