Ejemplos de Codigo de Visual C#

APLICACIONES DE CONSOLA
<<CREANDO UNA ESTRUCTURA LLAMADA ESTUDIANTE>>

//en este trozo de codigo declararemos una estructura llamada estudiante  que contiene  los siguientes campos:
1-Una variable de tipo string para almacenar el nombre del estudiante.
2-Una variable entera para almacenar la edad.
3-Un arreglo de strings para almacenar el nombre de las asignaturas
4-Un arreglo de enteros para almacenar las notas de cada una de las asignaturas
y tambien contrendra 2 funciones una que se llamara leer y la otra se llama mostrar
y en el main tendra lo siguiente:
1-un arreglo de estructuras de tipo Estudiante cuyo tamaño será pedido por
teclado.
2-A continuación pedir los datos de cada estructura utilizando la función Leer y mostrar los datos de cada
estructura utilizando la función Mostrar.


//INICIO DE CODIGO

using System;
using System.Collections.Generic;
using System.Text;


namespace Pract_Estudiante
{
class Program
{
  public struct estudiante //DECLARAMOS LA ESTRUCTURA LLAMADA ESTUDIANTE
{
//LOS DATOS MIEMBROS DE TIPO PUBLICO
  public string nombre;
public int edad;
public string[] asignaturas;
public int[] notas;
};


static estudiante[] e; //Arreglo de estruturas de tipo estudiante
//-------------------------------------FUNCION LEER----------------------------------
public static void leer(ref estudiante est)
{
int temp_clases = 0;
Console.WriteLine("\nIngrese el nombre del estudiante: ");
est.nombre = Console.ReadLine();
do
{
Console.WriteLine("Ingrese su edad: ");
est.edad = Utils.dato_int();
}while(est.edad<=0);
do
{
Console.WriteLine("Ingrese el numero de asignaturas: ");
temp_clases = Utils.dato_int();
}while(temp_clases<=0 || temp_clases>9);
est.asignaturas = new string[temp_clases];
est.notas = new int[temp_clases];
Console.WriteLine("\n\n***Asignaturas***");
for (int i=0;i<temp_clases;i++)
{
Console.WriteLine("Asignatura["+(i+1)+"]:");
est.asignaturas[i] = Console.ReadLine();
do
{
Console.WriteLine("Nota["+(i+1)+"]:");
est.notas[i] = Utils.dato_int();
}while(est.notas[i]<=0 || est.notas[i]>100);
}
}
public static void mostrar(ref estudiante est)
{
Console.WriteLine("\nNombre: " + est.nombre + "\t\tEdad: " + est.edad);
Console.WriteLine("****Asignaturas***");
for (int i=0;i<est.asignaturas.Length;i++)
Console.WriteLine("Asignatura[" + (i + 1) + "]: " + est.asignaturas[i]+" ---> "+ "Nota[" + (i + 1) + "]:" + est.notas[i]);
}
//---------------------------------***FUNCION MAIN***-------------------------
public static void Main(string[] args)
{
int cant_est = 0;
do
{
Console.WriteLine("\nIngrese la cantidad de estudiantes: ");
cant_est = Utils.dato_int();
} while (cant_est <= 0);
e = new estudiante[cant_est]; //Inicializamos el arreglo de estudiantes
for (int i = 0; i < cant_est; i++)
leer(ref e[i]);
for (int j = 0; j < cant_est; j++)
mostrar(ref e[j]);
Console.ReadLine();
}
}
}
//ESTE SERIA EL RESULTADO
(CLICK EN LA IMAGEN PARA AGRANDARLA)

<<CREACION DE LAS CLASES CHORA Y CFICHA>>

1-  Debemos crear en primer lugar una nueva clase llamada Util que contenga las funciones necesarias para leer los
distintos tipos de datos y una función que permita imprimir un menú de opciones, el código es el siguiente:  

using System;
using System.Collections.Generic;
using System.Text;

namespace Ficha
{
public class Utils
{
public static short dato_short()
{
try
{
return Int16.Parse(Console.ReadLine());
}
catch (FormatException)
{
return Int16.MinValue; //Valor mas pequeño
}
}
public static int dato_int()
{
try
{
return (Int32.Parse(Console.ReadLine()));
}
catch (FormatException)
{
return (Int32.MinValue); //valor mas pequeño
}
}
public static long dato_long()
{
try
{
return (Int64.Parse(Console.ReadLine()));
}
catch (FormatException)
{
return (Int64.MinValue); //valor mas pequeño
}
}
public static float dato_float()
{
try
{
return (Single.Parse(Console.ReadLine()));
}
catch (FormatException)
{
return (Single.NaN); //No es un numero-Valor float
}
}
public static double dato_double()
{
try
{
return (double.Parse(Console.ReadLine()));
}
catch (FormatException)
{
return (double.NaN); //No es un numero-Valor double
}
}
public static char dato_char()
{
try
{
return (char.Parse(Console.ReadLine()));
}
catch (FormatException)
{
return (char.MinValue);
}
}
public static int menu(string[] opciones, int num_opciones)
{
int i;
int opcion = 0;
System.Console.WriteLine("\n_________________________\n\n");
for (i = 1; i <= num_opciones; ++i)
System.Console.WriteLine(" " + i + ".-" + opciones[i - 1]);
System.Console.WriteLine("_________________________\n\n");
do
{
System.Console.WriteLine("\nOpcion (1-" + num_opciones + "):");
opcion = dato_int();
} while (opcion < 1 || opcion > num_opciones);
return (opcion);
}
}
}


2-A continuación debemos  añadir al proyecto una nueva clase llamada CHora tal como se indica a continuación: 

using System;
using System.Collections.Generic;
using System.Text;

namespace Ficha
{
class Chora
{
private int horas;
private int minutos;
private int segundos;
private string formato; //Almacena "am", "pm" o "24"
public string get_formato() { return formato; } //Accede al formato
public Chora()
{
horas = 12;
minutos = 0;
segundos = 0;
formato = "AM";
Console.WriteLine("Constructor por defecto ha sido invocado(Clase Chora)...");
}
public Chora(int h, int m, int s, string f)
{
horas = h;
minutos = m;
segundos = s;
formato = f;
Console.WriteLine("Constructor con parametros ha sido invocado(Clase Chora)...");
}
public Chora(Chora hora)
{
horas = hora.horas;
minutos = hora.minutos;
segundos = hora.segundos;
formato = hora.formato;
Console.WriteLine("Constructor copia invocado(Clase Chora)...");
}
public bool format()
{
if (formato.ToUpper() == "AM" || formato.ToUpper()=="PM")
return true;
if(formato=="24")
return false;
return false;
}
public bool verificar_hora()
{
if (format()) //Si formato es AM o PM
{
if (horas > 0 && horas <= 12 && minutos > 0 && minutos <= 59 && segundos > 0 && segundos <= 59)
return true;
else
return false;
}
else if (!format()) //Si el formato es 24
{
if (horas > 0 && horas <= 24 && minutos > 0 && minutos <= 59 && segundos > 0 && segundos <= 59 && formato=="24")
return true;
else
return false;
}
else
return false;
}
public bool set_hora(int nhoras, int nminutos, int nsegundos, string nformnato)
{
horas = nhoras;
minutos = nminutos;
segundos = nsegundos;
formato = nformnato;
Console.WriteLine("Funcion set hora invocado(Clase Chora)...");
return verificar_hora();
}
public void get_hora(ref int nhoras, ref int nminutos, ref int nsegundos, ref string nformato)
{
nhoras = horas;
nminutos = minutos;
nsegundos = segundos;
nformato = formato;
}
public string imprimir_hora()
{
string cadena;
cadena = ("Hora: " + horas + " Minutos: " + minutos + " Segundos:" + segundos + " Formato: " + formato);
return cadena;
}
}

Luego añadimos una nueva clase al proyecto llamada CFicha, su funcionalidad es la siguiente:  

using System;
using System.Collections.Generic;
using System.Text;

namespace Ficha
{
class Cficha
{
private string nombre;
private char sexo;
private Chora hora_nacimiento;
public Cficha()
{
nombre = "";
sexo = 'i';
hora_nacimiento = new Chora();
Console.WriteLine("Constructor por defecto ha sido invocado(Clase Cficha)...");
}
public Cficha(string n, char sex, int h, int m, int s, string f)
{
hora_nacimiento = new Chora(h, m, s, f);
nombre = n;
sexo = sex;
Console.WriteLine("Constructor con parametros ha sido invocado(Clase Cficha)...");
}
public Cficha(Cficha obj)
{
hora_nacimiento = new Chora(obj.hora_nacimiento);
nombre = obj.nombre;
sexo = obj.sexo;
Console.WriteLine("Constructor copia invocado(Clase Cficha)...");
}
public virtual Cficha clonar()
{
return new Cficha(this);
//cficha temp;
//temp=new cficha(this); -Sin asterisco
//return temp;
}
public string get_nombre() { return nombre; }
public bool set_ficha(string n, char sex, int h, int m, int s, string f)
{
nombre = n;
sexo = sex;
Console.WriteLine("\nFuncion set ficha invocada(Clase Cficha)...");
hora_nacimiento.set_hora(h, m, s, f);
return hora_nacimiento.verificar_hora();
}
public void get_ficha(ref string n, ref char sex, ref int h, ref int m, ref int s, ref string f)
{
n = nombre;
sex = sexo;
hora_nacimiento.get_hora(ref h, ref m, ref s, ref f);
}
public virtual void mostrar()
{
Console.WriteLine("\nNombre: " + nombre + "\nSexo: " + sexo + "\n" + hora_nacimiento.imprimir_hora()+"\nFuncion mostrar invocada(Clase Cficha)...");
}
public virtual string imprimir_ficha()
{
string cadena;
cadena = "Nombre: " + nombre + "\nSexo:" + sexo + "\n" + hora_nacimiento.imprimir_hora();
return cadena;
}
}
}
 
Desde la función main ponemos  a prueba las funciones definidas creando objetos de la clase CFicha e invocando a las distintas funciones.

using System;
using System.Collections.Generic;
using System.Text;

namespace Ficha
{
class Program
{
static void Main(string[] args)
{
int h, m, s,control=0,b;
string n, f;
char sex;
Cficha fich=new Cficha();
  Cficha fich2 = new Cficha("German Caceres", 'M', 7, 40, 10, "AM");
Cficha fich3 = new Cficha(fich2);
Console.WriteLine("\nIngrese su nombre: ");
n = Console.ReadLine();
do
{
Console.WriteLine("Ingrese su sexo: ");
sex = Utils.dato_char();
}while(sex.ToString().ToUpper()!="M" && sex.ToString().ToUpper()!="F");
do
{
if (control == 0)
goto b;
else
Console.WriteLine("\n**Se ha ingresado erroneamente algun elemento en el tiempo**\n\t\t\tIntente de nuevo...");
b:
Console.WriteLine("Ingrese la hora: ");
h = Utils.dato_int();
Console.WriteLine("Ingrese los minutos: ");
m = Utils.dato_int();
Console.WriteLine("Ingrese los segundos: ");
s = Utils.dato_int();
Console.WriteLine("Ingrese el formato: ");
f = Console.ReadLine();
control = 1;
} while (!(fich.set_ficha(n,sex,h,m,s,f)));
fich.mostrar();
Console.ReadLine();
}
}
}
 

//ESTE SERIA EL RESULTADO 
 (CLICK EN LA IMAGEN PARA AGRANDARLA)

 <<DERIVACION DE LA CLASE  CENFERMO Y CEMPLEADO TOMANDO COMO CLASE BASE LA CLASE CFICHA E IMPLEMENTACION DE LA CLASE CHOSPITAL>> 
I-CREAR LA CLASE CEMPLEADO 
1-Creamos la clase CEmpleado  además de la funcionalidad heredada de la clase CFicha, los siguientes datos miembro privados:

string m_sCategoria; // (ej.: "Enfermera", "Médico"...)
  int m_nAntiguedad; // (ej.: 3

2-Se deben añadir a esta clase el constructor sin argumentos, constructor con argumentos constructor copia. Recuerde que se deben invocar a los correspondientes constructores de la clase base. 

3-La siguiente función miembro servirá para modificar el contenido de los objetos de la clase:

public bool SetEmpleado(string categoria, int antiguedad, string
nombre, char sexo, int h, int m, int s, string f)
 
4-La siguiente función miembro servirá para obtener el contenido de los objetos de la clase:

public void GetEmpleado(out string categoria, out int antiguedad, out
string nombre, out char sexo, out int h, out int m, out int s, out
string f)

NOTA: Se deben redefinir los métodos Mostrar, ToString y clonar. 


using System;
using System.Collections.Generic;
using System.Text;

namespace hospital
{
class CEmpleado : CFicha
{
private string m_sCategaria;
private int m_nAntiguedades;

public CEmpleado(): base()
{
m_sCategaria = "";
m_nAntiguedades = 0;
}

public CEmpleado(string cat, int ant, string nom, char sex, int h, int m, int s, string f): base(nom, sex, h, m, s, f)
{
m_sCategaria = cat;
m_nAntiguedades = ant;
}

public CEmpleado(CEmpleado empleado)
{
int h=0, m=0, s=0;
string f="",nom="";
char sex = '\0';
m_sCategaria = empleado.m_sCategaria;
m_nAntiguedades = empleado.m_nAntiguedades;
empleado.GetFicha(ref nom,ref sex,ref h, ref m, ref s, ref f);
new CFicha(new CFicha(nom, sex, h, m, s, f));
}

public bool SetEmpleado(string categoria, int antiguedad, string nombre, char sexo, int h, int m, int s, string f)
{
m_sCategaria = categoria;
m_nAntiguedades = antiguedad;
return(SetFicha(nombre, sexo, h, m, s, f));
}

public void GetEmpleado(out string categoria, out int antiguedad, out string nombre, out char sexo, out int h, out int m, out int s, out string f)
{
string nom="", fo="";
char sex='\0';
int ho = 0,mi=0,se=0;
categoria = m_sCategaria;
antiguedad = m_nAntiguedades;
GetFicha(ref nom, ref sex, ref ho, ref mi, ref se, ref fo);
nombre = nom;
sexo = sex;
h = ho;
m = mi;
s = se;
f = fo;
}

public override CFicha clonar()
{
return new CEmpleado(this);
}

public override void mostrar()
{
Console.WriteLine("datos del empleado\nANTIGUEDAD\tCATEGORIA\tNOMBRE\tSEXO\tHORA\n");
Console.WriteLine(toString() + base.toString() + "\n");
}

public override string toString()
{
return ("\t"+m_nAntiguedades + "\t"+ m_sCategaria + "\t\t");
}
}
}
II- CREAR LA CLASE CENFERMO
1-La clase CEnfermo (que también será derivada de CFicha) solo tendrá un dato miembro:

string m_sEnfermedad; // (ej.: "Bronquitis"...) 

2-Crear las  funciones Set y Get:

public bool SetEnfermo(string enfermedad, string nombre, char sexo,  int h, int m, int s, string f)

public void GetEnfermo(out string enfermedad, out string nombre, out char sexo, out int h, out int m, out int s, out string f)  

NOTA:El funcionamiento será análogo al de la clase CEmpleado.

using System;
using System.Collections.Generic;
using System.Text;

namespace hospital
{
class CEnfermo: CFicha
{
string m_senfermedad;
public CEnfermo(string enfermedad, string nom, char sex, int h, int m, int s, string f)
{
SetEnfermo(enfermedad, nom, sex, h, m, s, f);
}

public bool SetEnfermo(string enfermedad, string nom, char sex, int h, int m, int s, string f)
{
m_senfermedad = enfermedad;
return (SetFicha(nom,sex,h,m,s,f));
}

public void GetEnfermedad(out string enfermedad, out string nombre, out char sexo, out int h, out int m, out int s, out string f)
{
enfermedad=m_senfermedad;
string nom = "", fo = "";
char sex = '\0';
int ho = 0, mi = 0, se = 0;
GetFicha(ref nom, ref sex , ref ho, ref mi , ref se , ref fo);
nombre = nom;
sexo = sex;
h = ho;
m = mi;
s = se;
f = fo;
}

public override void mostrar()
{
Console.WriteLine("datos del Enfermo\nENFERMEDAD\tNOMBRE\tSEXO\tHORA\n");
Console.WriteLine("\t"+m_senfermedad + "\t" + base.toString() + "\n");
}
}
}
 
  III- CREAR LA CLASE CHOSPITAL

1- Declarará una nueva clase CHospital mediante la cuál se implementará un array de objetos de tipo
empleado o enfermo. Habrá que declarar y definir.
2-Un constructor que crea el array de objetos. Recibirá como parámetro el número máximo de elementos del array.  
3-El constructor copia. Observe que la clase CHospital contiene referencias a objetos. Eso significa que el constructor copia por omisión sólo copia direcciones, no duplicarán los objetos referenciados.  4-Una función SetPersona(), que permita almacenar en el array una referencia a los datos de cada
persona, ya sea empleado o enfermo.
5-Una función MostrarGente(), que llama a la función Mostrar() para cada uno de los empleados o
enfermos del array.
6-El programa principal se contendrá un menú como el siguiente:

1. Introducir empleado.
2. Introducir enfermo.
3. Buscar por nombre.
4. Mostrar hospital.
5. Copia de seguridad del hospital.
6. Restaurar copia de seguridad.
7. Salir. 

La opción 4 mostrará todas las personas del hospital, empleados y enfermos (hacer una pausa cuando se llene la
pantalla o por cada persona mostrada).

La opción 5 hará un duplicado del objeto hospital actual. Una vez hecha la copia de seguridad suponer que,
haciendo pruebas, se altera la composición del hospital (por ejemplo, añadiendo nuevos enfermos) y se desea
volver a la composición que había hecho cuando se hizo la copia de seguridad. La opción 6 permitirá esta última
acción. Se puede comprobar con la opción 4.


 using System;
using System.Collections.Generic;
using System.Text;

namespace hospital
{
class Chospita
{
public CFicha[] mihospital;

public Chospita(int max)
{
mihospital= new CFicha[max];
}

public Chospita(Chospita seghospital)
{
mihospital = new CFicha [seghospital.mihospital.Length-1];
for (int i = 0; i < mihospital.Length; i++)
{
mihospital[i] = new CFicha(seghospital.mihospital[i].clonar());

}
}

public void SetPersona(int index, int tipo)
{
int h, m, s,ant;
string form, nom,cat,enf;
char sex;
CHora temp;
Console.WriteLine("Introduzca el nombre: ");
nom=Console.ReadLine();
do{
Console.WriteLine("Introduzca el sexo: ");
sex = util.datochar();
if (sex.ToString().ToLower() != "m" && sex.ToString().ToLower() != "f")
Console.WriteLine("Introduzca nuevamente el sexo(m ó f)");
} while (sex.ToString().ToLower() != "m" && sex.ToString().ToLower() != "f");

do{
Console.WriteLine("Introduzca el hora : ");
h = util.datoInt();
Console.WriteLine("minutos: ");
m = util.datoInt();
Console.WriteLine("Segundo: ");
s = util.datoInt();
Console.WriteLine("formato: ");
do{
form = Console.ReadLine();
if (form.ToLower() != "am" && form.ToLower() != "pm" && form != "24")
{
Console.WriteLine("Introduzca nuevamente el formato de la hora: ");
}
} while (form.ToLower() != "am" && form.ToLower() != "pm" && form != "24");
temp= new CHora(h,m,s,form);
if (!temp.verificarHora())
{
Console.WriteLine("No es correcto el formato de la hora:minuto:segundo -- formato...\n");
}
}while(!temp.verificarHora());
if (tipo == 1)
{
Console.WriteLine("Introduzca la categoria: ");
cat = Console.ReadLine();
Console.WriteLine("Introduzca el antiguedad: ");
ant = util.datoInt();
mihospital[index] = new CEmpleado(cat,ant,nom,sex,h,m,s,form );
}
if (tipo == 2)
{
Console.WriteLine("Introduzca la enfermedad");
enf=Console.ReadLine();
mihospital[index] = new CEnfermo(enf,nom,sex,h,m,s,form );
}
}

public void MostrarPersonas()
{
for (int i = 0; i < mihospital.Rank; i++)
{
mihospital[i].mostrar();
}
}
}
}

IV- AGREGARLE LAS CLASES CHORA,CFICHA Y UTIL DEL PROYECTO ANTERIOR 

using System;
using System.Collections.Generic;
using System.Text;

namespace hospital
{
class CHora
{
private int horas;
private int minutos;
private int segundos;
private string formato;
public CHora()
{
horas = 0;
minutos = 0;
segundos = 1;
formato = "24";
}

public CHora(int h, int m, int s, string f)
{
horas = h;
minutos = m;
segundos = s;
formato = f;
}

public CHora(CHora hora)
{
horas = hora.horas;
minutos = hora.minutos;
segundos = hora.segundos;
formato = hora.formato;
}

public bool format()
{
bool forma = false;
if (formato == "24")
forma = true;
return (forma);
}

public bool verificarHora()
{
bool fo=false;
if (format())
{
if (horas >= 0 && minutos >= 0 && segundos >= 0 && horas <= 23 && minutos <= 59 && segundos <= 59)
fo = true;
}
else
{
if (horas > 0 && minutos >= 0 && segundos >= 0 && horas < 13 && minutos < 60 && segundos < 60)
fo = true;
}
return fo;
}

public bool setHora(ref int hora, ref int minuto, ref int segundo, ref string format)
{
horas = hora;
minutos = minuto;
segundos = segundo;
formato = format;
return(verificarHora());
}

public void GetHora(ref int hora, ref int minuto, ref int segundo, ref string forma)
{
hora = horas;
minuto = minutos;
segundo = segundos;
forma = formato;
}

public string tostring()
{
int h=0, m=0, s=0;
string f = "";
this.GetHora(ref h, ref m, ref s, ref f);
return (h +":"+ m +":"+":"+ s +"--"+ f);
}
}

}

************************************************************************************
using System;
using System.Collections.Generic;
using System.Text;

namespace hospital
{
class CFicha
{
private string nombre;
private char sexo;
private CHora Horanacimiento;

public CFicha()
{
nombre = "";
sexo = '\0';
Horanacimiento= new CHora();
}

public CFicha(string nom, char sex, int h, int m, int s, string f)
{
nombre = nom;
sexo = sex;
Horanacimiento= new CHora(h, m, s, f);
}

public CFicha(CFicha f)
{
nombre = f.nombre;
sexo = f.sexo;
Horanacimiento= new CHora(f.Horanacimiento);
}

public virtual CFicha clonar()
{
return new CFicha(this);
}

public string GetNombre()
{
return(nombre);
}

public bool SetFicha(string nom, char sex, int h, int m, int s, string f)
{
nombre = nom;
sexo = sex;
Horanacimiento= new CHora (h, m, s, f);
return(Horanacimiento.verificarHora());
}

public void GetFicha(ref string nom, ref char sex, ref int h, ref int m, ref int s, ref string f)
{
nom = nombre;
sex = sexo;
Horanacimiento.GetHora(ref h, ref m, ref s, ref f);
}

public virtual void mostrar()
{
Console.WriteLine("Contenido de la ficha\n");
Console.WriteLine(toString());
}

public virtual string toString()
{
return (nombre + "\t" + sexo + "\t" + Horanacimiento.tostring());
}
}
}

**************************************************************************************
using System;
using System.Collections.Generic;
using System.Text;

namespace hospital
{
public class util
{
public static short datoShort()
{
try
{
return Int16.Parse(Console.ReadLine());
}
catch(FormatException)
{
return Int16.MinValue;
}
}
public static int datoInt()
{
try
{
return Int32.Parse(Console.ReadLine());
}
catch (FormatException)
{
return datoInt();
}
}

public static long datoLong()
{
try
{
return Int64.Parse(Console.ReadLine());
}
catch (FormatException)
{
return Int64.MinValue;
}
}
public static float datoFloat()
{
try
{
return Single.Parse(Console.ReadLine());
}
catch (FormatException)
{
return Single.NaN;
}
}
public static char datochar()
{
try
{
return char.Parse(Console.ReadLine());
}
catch (FormatException)
{
return ('\0');
}
}

public static Double datoDouble()
{
try
{
return Double.Parse(Console.ReadLine());
}
catch (FormatException)
{
return Double.NaN;
}
}
public static int menu(string[] opciones, int numopciones)
{
int i;
int opcion = 0;
System.Console.WriteLine("\n___________________________________\n\n");
for (i = 1; i <= numopciones; ++i)
System.Console.WriteLine(" " + i + ".- " + opciones[i - 1]);
System.Console.WriteLine("___________________________________\n");

do
{
System.Console.WriteLine("\nOpcion (1 - " + numopciones + "): ");
opcion = datoInt();
}
while(opcion<1 || opcion>numopciones);
return opcion;
}
  }
}
 
//ESTE SERIA EL RESULTADO






 
 

 




No hay comentarios:

Publicar un comentario