Hola a todos, hoy os dejo una serie de ejercicios propuestos y resueltos de POO en C#.
Todos los ejercicios que proponemos están resueltos en este mismo post, intenta hacerlo por ti mismo y si te quedas atascado puedes mirar la solución. Recuerda, que no tiene por que estar igual tu solución con la del post, el objetivo es que aprendas no que me copies la solución.
Te recomiendo que uses mensajes de trazas, donde te sean necesarios. Si tienes problemas también puedes usar el depurador.
1. Crea una clase Coche con las siguientes propiedades:
– ID
– Marca
– Modelo
– KM
– Precio
Debemos crear un constructor donde le pasemos los valores.
Crea sus get y set de cada propiedad.
Crea el metodo toString.
— Coche
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO1
{
class Coche
{
private int _id;
private String _marca;
private String _modelo;
private int _km;
private double _precio;
public Coche(int id, string marca, string modelo, int km, double precio)
{
this._id = id;
this._marca = marca;
this._modelo = modelo;
this._km = km;
this._precio = precio;
}
public int id { get => _id; set => _id = value; }
public string marca { get => _marca; set => _marca = value; }
public string modelo { get => _modelo; set => _modelo = value; }
public int km { get => _km; set => _km = value; }
public double precio { get => _precio; set => _precio = value; }
public override string ToString()
{
return "Marca: " + marca + ", modelo: " + modelo +
" con un precio de " + precio;
}
}
}
|
— Program
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO1
{
class Program
{
static void Main(string[] args)
{
// Creamos un objeto coche
Coche c = new Coche(1, "BMW", "4", 100, 12000);
// get de precio de coche
Console.WriteLine(c.precio);
// get de marca de coche
Console.WriteLine(c.marca);
// Modifico el precio del coche con el set
c.precio = 15000;
// Vuelvo a mostrar para ver si se ha modificado
Console.WriteLine(c.precio);
// Muestro el estado completo
Console.WriteLine(c.ToString());
Console.ReadLine();
}
}
}
|
2. Crea una clase Concesionario que gestione una serie de coches.
Tendra un array de objetos coches (anterior ejercicio)
y un limite de coches.
Crearemos los siguientes metodos:
– aniadirCoche(Coche c)
– mostrarCoches()
– vaciarCoches()
– eliminarCoche(Coche c)
— Coche
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO2
{
class Coche
{
private int _id;
private String _marca;
private String _modelo;
private int _km;
private double _precio;
public Coche(int id, string marca, string modelo, int km, double precio)
{
this._id = id;
this._marca = marca;
this._modelo = modelo;
this._km = km;
this._precio = precio;
}
public int id { get => _id; set => _id = value; }
public string marca { get => _marca; set => _marca = value; }
public string modelo { get => _modelo; set => _modelo = value; }
public int km { get => _km; set => _km = value; }
public double precio { get => _precio; set => _precio = value; }
public override string ToString()
{
return "Marca: " + marca + ", modelo: " + modelo +
" con un precio de " + precio;
}
}
}
|
— Concesionario
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO2
{
class Concesionario
{
private Coche[] _coches;
private int _limite;
private int _numCoches;
public Concesionario(int limite)
{
this._coches = new Coche[limite];
_limite = limite;
_numCoches = 0;
}
public void aniadirCoche(Coche c)
{
if (c != null && _numCoches < _coches.Length)
{
_coches[_numCoches] = c;
_numCoches++;
}
}
public void mostrarCoches()
{
for (int i=0; i< _numCoches; i++)
{
Console.WriteLine(_coches[i].ToString());
}
}
public void vaciarCoches()
{
this._coches = new Coche[_limite];
_numCoches = 0;
}
public void eliminarCoche(Coche c)
{
if (c!= null && _numCoches != 0)
{
int posicion = -1;
for (int i=0; i< _numCoches; i++)
{
if (c.id == _coches[i].id)
{
posicion = i;
}
}
if (posicion == -1)
{
Console.WriteLine("No existe el coche");
}
else
{
_coches[posicion] = null;
for (int i = posicion;i<_numCoches;i++)
{
_coches[i] = _coches[i+1];
}
_numCoches--;
}
}
}
}
}
|
— Program
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO2
{
class Program
{
static void Main(string[] args)
{
Concesionario concesionario = new Concesionario(10);
Coche c1 = new Coche(1,"BMW", "4", 1000, 12000);
Coche c2 = new Coche(2, "Toyota", "auris", 0, 12000);
Coche c3 = new Coche(3, "Seat", "Ibiza", 2000, 15000);
Coche c4 = new Coche(4, "Ferrari", "rosca", 1000, 20000);
Coche c5 = new Coche(5, "Peugeout", "206", 100000, 30000);
concesionario.aniadirCoche(c1);
concesionario.aniadirCoche(c2);
concesionario.aniadirCoche(c3);
concesionario.aniadirCoche(c4);
concesionario.aniadirCoche(c5);
Console.WriteLine("Todos los coches");
concesionario.mostrarCoches();
concesionario.eliminarCoche(c3);
concesionario.eliminarCoche(c1);
Console.WriteLine("Elimino dos coches");
concesionario.mostrarCoches();
concesionario.aniadirCoche(c3);
Console.WriteLine("Añadir un coche mas");
concesionario.mostrarCoches();
Console.WriteLine("vacio");
concesionario.vaciarCoches();
concesionario.mostrarCoches();
Console.ReadLine();
}
}
}
|
3. Crea una clase Aleatorios
Como atributo tendra un Random.
Tendra los siguientes metodos:
– Generar un numero entre 2 numeros
– Generar un array de numeros entre dos numeros
— Aleatorios
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO3
{
class Aleatorios
{
private Random _random;
public Aleatorios()
{
this._random = new Random();
}
public int generarNumeroAleatorio(int min, int max)
{
if (min > max)
{
int aux = min;
min = max;
max = aux;
}
return this._random.Next(min, max+1);
}
public int[] generarNumerosAleatorios(
int longitud,
int min,
int max)
{
if (longitud <= 0)
{
return null;
}
int[] numeros = new int[longitud];
for (int i=0; i< numeros.Length ;i++)
{
numeros[i] = generarNumeroAleatorio(min, max);
}
return numeros;
}
}
}
|
— Program
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO3
{
class Program
{
static void Main(string[] args)
{
Aleatorios a = new Aleatorios();
Console.WriteLine("Genero 20 numero entre 1 y 20");
for (int i=0; i<20 ;i++)
{
Console.WriteLine(a.generarNumeroAleatorio(1,20));
}
Console.WriteLine("Genero 20 numeros entre 1 y 20 en un array");
int[] arr = a.generarNumerosAleatorios(-5, 1, 20);
for (int i=0; arr!= null && i < arr.Length ;i++)
{
Console.WriteLine(arr[i]);
}
Console.ReadLine();
}
}
}
|
4. Usando la clase anterior de Aleatorios
– Generar un array de números no repetidos entre dos números
— Aleatorios
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio_POO_DDR_4
{
class Aleatorios
{
private Random _random;
public Aleatorios()
{
this._random = new Random();
}
public int generarNumeroAleatorio(int min, int max)
{
if (min > max)
{
int aux = min;
min = max;
max = aux;
}
return this._random.Next(min, max + 1);
}
public int[] generarNumerosAleatorios(int longitud, int min, int max)
{
if (longitud <= 0)
{
return null;
}
int[] numeros = new int[longitud];
for (int i = 0; i < numeros.Length; i++)
{
numeros[i] = generarNumeroAleatorio(min, max);
}
return numeros;
}
public int[] generarNumerosAleatoriosNoRepetidos(
int longitud,
int min,
int max)
{
if (min > max)
{
int aux = min;
min = max;
max = aux;
}
if (longitud <= 0 || (max - min) < longitud-1)
{
return null;
}
int[] numeros = new int[longitud];
bool repetido;
int numero;
int indice = 0;
while (indice < numeros.Length)
{
repetido = false;
numero = generarNumeroAleatorio(min, max);
for (int i = 0; i < indice; i++)
{
if (numeros[i] == numero)
{
repetido = true;
}
}
if (!repetido)
{
numeros[indice] = numero;
indice++;
}
}
return numeros;
}
}
}
|
— Program
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio_POO_DDR_4
{
class Program
{
static void Main(string[] args)
{
Aleatorios a = new Aleatorios();
int[] numeros = a.generarNumerosAleatoriosNoRepetidos(5, 0, 100);
if (numeros != null)
{
for (int i = 0; i < numeros.Length; i++)
{
Console.WriteLine(numeros[i]);
}
}
else
{
Console.WriteLine("Revisa los parametros");
}
Console.ReadLine();
}
}
}
|
5. Crea una clase Ordenador con los siguientes atributos:
– tamanio disco (GB)
– tamanio disco max (GB)
– encendido
Los metodos a añadir son:
– aniadirDatos(int datos): añade informacion al disco duro, si supera el maximo del tamaño del disco, el tamanio del disco sera el maximo posible. Solo si esta encendido el ordenador.
– eliminarDatos(int datos): elimina informacion al disco duro, si el tamaño del disco es menor que 0, el tamanio del disco se quedara a 0. Solo si esta encendido el ordenador.
– encender(): enciende el ordenador.
– apagar(): apaga el ordenador.
— Ordenador
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO5
{
class Ordenador
{
private int tamanioGB;
private int tamanioGBMax;
private bool encendido;
private const int TAMANIO_DEFECTO = 100;
public Ordenador(int tamanioGBMax)
{
this.tamanioGB = 0;
this.encendido = false;
if (tamanioGBMax <= 0)
{
this.tamanioGBMax = TAMANIO_DEFECTO;
}
else
{
this.tamanioGBMax = tamanioGBMax;
}
}
public void aniadirDatos(int datos)
{
if (this.encendido)
{
if (datos <= 0)
{
Console.WriteLine("Los GB tienen que ser mayor que 0");
}
else
{
if (this.tamanioGB + datos >= this.tamanioGBMax)
{
this.tamanioGB = this.tamanioGBMax;
Console.WriteLine("Disco duro lleno");
}
else
{
this.tamanioGB += datos;
Console.WriteLine("Se ha añadido informacion, actual: "
+ this.tamanioGB);
}
}
}
else
{
Console.WriteLine("El ordenador debe estar encendido");
}
}
public void eliminarDatos(int datos)
{
if (this.encendido)
{
if (datos <= 0)
{
Console.WriteLine("Los GB tienen que ser mayor que 0");
}
else
{
if (this.tamanioGB - datos <= 0)
{
this.tamanioGB = 0;
Console.WriteLine("Disco duro vacio");
}
else
{
this.tamanioGB -= datos;
Console.WriteLine("Se ha eliminado informacion, actual: "
+ this.tamanioGB);
}
}
}
else
{
Console.WriteLine("El ordenador debe estar encendido");
}
}
public void encender()
{
this.encendido = true;
}
public void apagar()
{
this.encendido = false;
}
}
}
|
— Program
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO5
{
class Program
{
static void Main(string[] args)
{
Ordenador ordenador = new Ordenador(500);
ordenador.encender();
ordenador.aniadirDatos(200);
ordenador.apagar();
ordenador.eliminarDatos(100);
Console.ReadLine();
}
}
}
|
6. Crea la clase ConexionAccess para conectar access y C#.
Los métodos o funciones serán las siguientes:
– open(): Abre la base de datos.
– close(): Cierra la base de datos.
– executeQuery(string sql): Dataset : devuelve un dataset de la consulta.
– executeInstruction(string sql): bool : devuelve si se ejecuto o no la instruccion.
— ConexionAccess
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO6
{
class ConexionAccess
{
private OleDbConnection connection;
public ConexionAccess(string path)
{
this.connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|" + path);
}
public void open()
{
this.connection.Open();
}
public void close()
{
this.connection.Close();
}
public DataSet executeQuery(string sql)
{
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, this.connection);
DataSet d = new DataSet();
adapter.Fill(d);
return d;
}
public bool executeInstruction(string sql)
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = this.connection;
cmd.CommandText = @sql;
return cmd.ExecuteNonQuery() > 0;
}
}
}
|
— Program
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO6
{
class Program
{
static void Main(string[] args)
{
ConexionAccess con = new ConexionAccess("Database.accdb");
con.open();
DataSet d = con.executeQuery("SELECT * FROM clientes");
foreach(DataRow row in d.Tables[0].Rows)
{
Console.WriteLine("ID: " + row["ID"]);
Console.WriteLine("nombre: " + row["nombre"]);
Console.WriteLine("apellidos: " + row["apellidos"]);
Console.WriteLine("edad: " + row["edad"]);
Console.WriteLine();
}
con.close();
Console.ReadLine();
}
}
}
|
7. Crea una clase Vehiculo que sea la misma que la clase Coche que trabajamos en el 1º video.
Crea dos clases hijas: Coche y Moto
La clase Coche tendra un atributo airbag, sobrescribe el metodo precio, si tiene airbag el precio aumentara 200.
La clase Moto tendra un atributo sidecar, sobrescribe el metodo precio, si tiene sidecar el precio aumentara 50.
— Vehiculo
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO7
{
class Vehiculo {
private int _id;
private String _marca;
private String _modelo;
private int _km;
private double _precio;
public Vehiculo(int id, string marca, string modelo, int km, double precio)
{
this._id = id;
this._marca = marca;
this._modelo = modelo;
this._km = km;
this._precio = precio;
}
public int id { get => _id; set => _id = value; }
public string marca { get => _marca; set => _marca = value; }
public string modelo { get => _modelo; set => _modelo = value; }
public int km { get => _km; set => _km = value; }
public virtual double precio { get => _precio; set => _precio = value; }
public override string ToString()
{
return "Marca: " + marca + ", modelo: " + modelo + " con un precio de " + precio;
}
}
}
|
— Coche
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO7
{
class Coche:Vehiculo
{
private bool _airbag;
public Coche(int id, string marca, string modelo,
int km, double precio, bool airbag)
:base(id,marca,modelo, km, precio)
{
this.airbag = airbag;
}
public bool airbag { get => _airbag; set => _airbag = value; }
public override double precio
{
get
{
if (this.airbag)
{
return base.precio + 200;
}
else
{
return base.precio;
}
}
}
public override string ToString()
{
if (this.airbag)
{
return base.ToString() + " y tiene airbag";
}
else
{
return base.ToString() + " y no tiene airbag";
}
}
}
}
|
— Moto
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO7
{
class Moto:Vehiculo
{
private bool _sidecar;
public Moto(int id, string marca, string modelo,
int km, double precio, bool sidecar)
: base(id, marca, modelo, km, precio)
{
this.sidecar = sidecar;
}
public bool sidecar { get => _sidecar; set => _sidecar = value; }
public override double precio
{
get
{
if (this.sidecar)
{
return base.precio + 50;
}
else
{
return base.precio;
}
}
}
public override string ToString()
{
if (this.sidecar)
{
return base.ToString() + " y tiene sidecar";
}
else
{
return base.ToString() + " y no tiene sidecar";
}
}
}
}
|
— Program
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POO7
{
class Program
{
static void Main(string[] args)
{
Coche c = new Coche(1, "BMW", "1", 500, 10000, false);
Moto m = new Moto(2, "Toyota", "2", 100, 5000, true);
Console.WriteLine("Precio coche: " + c.precio);
Console.WriteLine("Precio moto: " + m.precio);
Console.WriteLine(c.ToString());
Console.WriteLine(m.ToString());
Console.ReadLine();
}
}
}
|
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
Deja una respuesta