Programa que realiza la simulación de un Cajero Automático en Java Netbeans 6



Comments



Description

Programa que realiza la simulación de un Cajero Automático en Java Netbeans 6.8 El programa consiste en que si se introduce la contraseña y esta es correcta podra acceder a su cuenta y al menu de opciones: +++++++++++++Simulacion de Cajero+++++++++++ 1.-Transferencia 2.-Retiro 3.-Consulta El programa posee dos clases: Cuenta y Transferencia las cuales heredan de la clase padre Clase_Polimorfismo la misma que es abstracta. Ademas contiene una Interface: Interface la que contiene un solo metodo y una constante declarada la misma que ya contiene su valor. Sin dejar atras de la clase ejecutora la cual contiene manejo de excepciones para controlar los digitos de la contraseña.... Clase Principal-Ejecutora del Programa package Simula_Cajero; import java.io.*; public class Principal_Cajero { public static InputStreamReader Leer = new InputStreamReader(System.in); public static BufferedReader Teclado = new BufferedReader(Leer); public static void main(String[] args) throws IOException { Clase_Polimorfismo [] maru = new Clase_Polimorfismo[3]; maru[0] =new Cuenta (500,"Luis"); maru[1] =new Cuenta (700,"Xander"); maru[2] =new Cuenta (600,"Missael"); Clase_Polimorfismo [] leo = new Clase_Polimorfismo[3]; leo[0]= new Transferencia(0,"Luis"); leo[1]= new Transferencia(0,"Xander"); leo[2]= new Transferencia(0,"Missael"); int contr[]= new int [3]; contr[0]=1000; contr[1]=2000; contr[2]=3000; int cta[]= new int[3]; cta[0]=100; cta[1]=200; cta[2]=300; int m=0,l=0,q=0; boolean falso=false; do{ try{ falso=false; do{ System.out.println(" INTRODUSCA SU CONTRASEÑA:"); int usuario=Integer.parseInt(Teclado.readLine()); if(usuario==contr[i]){ m=i; System.out.println(" BIENVENIDO Al SISTEMA DE CAJERO AUTOMATICO "); l=1; q=2; maru[i].Informacion();}} if(l==0) System.out.println(" CONTRASEÑA ERRONEA "); if(q !=2){ System.out.println(" PRESIONE 1 PARA VOLVER"); q=Integer.parseInt(Teclado.readLine()); }}while(q==1);} catch(NumberFormatException e ){falso=true; System.out.println(" ERROR CONTRASEÑA INVALIDA"+"SOLO NUMERO "+e); }}while(falso); if(l==1){ int o; do{ System.out.println("Que desea hacer:"); System.out.println("1.-Transferencia"); System.out.println("2.-Retiro"); System.out.println("3.-Consulta"); System.out.println("Ingrese opcion:"); o=Integer.parseInt(Teclado.readLine()); switch(o){ case 1: boolean mar=false; System.out.println(" INTRODUSCA EL NUMERO DE CUENTA"); int usuario=Integer.parseInt(Teclado.readLine()); if(usuario==cta[i]){mar=true; System.out.println(" Introdusca la cantidad a Transferir:"); int cant=Integer.parseInt(Teclado.readLine()); int lu=maru[m].Saldo(); if(cant<=lu){ maru[m].Transferencia(cant); leo[i].Transferencia(cant); leo[i].Informacion(); }else System.out.println(" NO HAY SUFICIENTE DINERO");}} if(mar==false){ System.out.println(" NUMERO DE CUENTA ERRONEO");} maru[m].Informacion(); break; case 2: boolean my=false; do{ my=false; try{ System.out.println(" Introduzca la Cantidad a Retirar:"); int cant1=Integer.parseInt(Teclado.readLine()); if(cant1<=maru[m].Saldo()){ maru[m].Retiro(cant1); }else System.out.println(" NO HAY SUFICIENTE DINERO PARA RETIRAR"); maru[m].Informacion(); }catch(NumberFormatException e ){my=true; System.out.println(" ERROR"+"SOLO NUMERO "+e); }}while(my); break; case 3: System.out.println(" *************+BIENVENIDO +************* "); maru[m].Informacion(); } Clase Polimorfismo package Simula_Cajero; public abstract class Clase_Polimorfismo { protected int sald; protected String nom; public Clase_Polimorfismo(int sald, String nom) { this.sald = sald; this.nom = nom; } public abstract int Saldo(); public abstract int Transferencia(int t); public abstract void Retiro (int r); public abstract void Informacion(); } Clase Cuenta package Simula_Cajero; public class Cuenta extends Clase_Polimorfismo implements Interface { public static int sald_ini=5; public Cuenta(int sald, String nom) { super(sald, nom); } @Override public int Saldo() { return this.sald; } @Override public int Transferencia(int t) { if(t>5){ int trans=(t*sald_ini)/100; this.sald-=t+trans;} else System.out.println("No se puede Transferir menos de $5"); return this.sald; } @Override public void Retiro(int r) { if(r>5){ int re=(r*sald_ini)/100; this.sald-=r+re;}else System.out.println("No se puede Retirar menos de $5"); } public int Consulta_Saldo() { return this.sald; } @Override public void Informacion() { System.out.println("Hola:" +this.nom); System.out.println("Su Saldo actual es:" +this.Consulta_Saldo()); }} Interface public int imp=2. } @Override public void Retiro(int r) { if(r >5){ int ret=(r*sald_ini)/100.package Simula_Cajero.println("El Saldo Transferido es:" + this.sald). public class Transferencia extends Clase_Polimorfismo { public static int sald_ini=5.println("No se puede retirar menos del Saldo Inicial").out. }} Ejecucion del programa con la opcion Transferencia . this. nom). String nom) { super(sald.sald. } Clase Transferencia package Simula_Cajero.sald+=t. } @Override public int Transferencia(int t) { return this. public Transferencia(int sald.} @Override public int Saldo() { return this. } @Override public void Informacion() { System. public interface Interface { public int Consulta_Saldo().out. }else System.sald=r+ret. Ejecucion del programa con la opcion Retiro . Ejecucion del programa con la opcion Consulta . private int num2. //Creamos un método constructor parametrizado public SumaNum(int num1. CLASE NORMAL package Operaciones. Nota: Para realizar este programa necesitamos de una clase principal y otra normal.num1 = num1. this. int num2) { this.num2 = num2. public class SumaNum { private int num1. } .Programa Nº1 Un Programa en Java Netbeans que nos permita sumar dos números. Primer Numero").. public class Principal { public static InputStreamReader leer=new InputStreamReader(System. public static void main(String[] args) throws IOException{ System.out.num1+this. } } EJECUCIÓN DEL PROGRAMA EN PANTALLA 1. System.parseInt(teclado.//Creamos un método constructor por default public SumaNum() { this. Segundo Numero").*. import java.out. int num11=Integer. System.io. public static BufferedReader teclado=new BufferedReader(leer).println("Ing.readLine()). System.in).readLine()).num2. } } CLASE PRINCIPAL package Operaciones.println("Suma de dos Números").OpeSuma().num22).println("La suma es:"+suma).: 5) . int num22=Integer.out. int suma=objeto.parseInt(teclado. return sum.out. } //Creamos un método convencional public int OpeSuma(){ int sum=this.println("Ing.num1 = 0. SumaNum objeto=new SumaNum(num11.Nos pide ingresar el primer Número a sumar (Ej. : 4) 3. CLASE NORMAL package Num_Perfecto. Verificar cuales y cuántos de ellos son números perfectos.2.Por ultimo nos obtenemos el resultado de la suma Programa Nº2 Implementar un programa en el cual se implemente un proceso que me permita leer 10 valores numéricos desde el teclado.-Nos pide ingresar el segundo Número a sumar (Ej. public class Perfecto { private int num. Número Perfecto: es igual a la suma de sus divisores excepto para sí mismo.. //Creamos un método constructor por default public Perfecto() { . :Para realizar este programa tenemos que saber que es un número perfecto. } //Creamos un método convencional public boolean VerificarPerfecto(int num){ this.println("Numero Perfecto").out.i<10. System.num%2)==0) sum+=t. else return false.println("Ing. public static BufferedReader teclado=new BufferedReader(leer).*. } if(sum==this. 10 Numeros").num=num. import java.num) return true.io.num if((this. int sum=0. for(int i=0. public static void main(String[] args)throws IOException { System.num=0.cont=0. } } CLASE PRINCIPAL package Num_Perfecto. t++.in).out.i++){ . int num=0.this. public class Principal { public static InputStreamReader leer=new InputStreamReader(System.t=1. Perfecto objeto=new Perfecto(). while(this. 7.parseInt(teclado.6.println("Numeros Perfectos encontrados:"+cont).5.num=Integer. } } System.3.4.readLine()).out.9. if(objeto.out.2.8.: 1.12) 2. cont ++.-Nos muestra el total de números perfectos encontrados .println("Numero Perfecto"+num).-Nos pide ingresar 10 Números (Ej.VerificarPerfecto(num)){ System. } } EJECUCIÓN DEL PROGRAMA EN PANTALLA 1. } //Creamos un método convencional public boolean verificarSiNoPrimo(){ int cont=0. public class Aleatorio { private int valor.p<=this. } } CLASE PRINCIPAL . //Creamos un método constructor por default public Aleatorio() { this.valor. else return false.valor = valor.valor=0. CLASE NORMAL package pckAleatorio.valor%p==0) cont ++. } //Creamos un método constructor parametrizado con propiedad setter public void setValor(int valor) { this.. Para realizar este programa necesitamos crear un objeto Randómico que genere valores randómicos. for(int p=0.} if(cont <=2) return true.p++){ if(this.Programa Nº3 Implementar una clase que me permita leer 10 números aleatorios. determinar cuáles de ellos son números primos. package pckAleatorio. for(int i=1. } } } } EJECUCIÓN DEL PROGRAMA EN PANTALLA 1.Random. System.nextInt(30). i++){ int num=rnd.println(num). i<=10.out.out.setValor(num).println(num).Obtenemos el resultado en Pantalla.. if(viernes. public class Principal { public static void main(String[] args) { Random rnd=new Random().out. Aleatorio viernes=new Aleatorio(). .println("No es un Número Primo" ).out. System. viernes.util.} else{ System.verificarSiNoPrimo()){ System.println("Es un Número Primo " ). import java. int y2) { this. private int y2. . //Creamos un método constructor parametrizado public Dis_Puntos(int x1. int x2. private int x2. private int y1.Programa Nº4 Implementar un programa que permita calcular la distancia entre dos Puntos Para realizar este programa tenemos que saber la fórmula para la distancia que es: <!--[if !msEquation]--> <!--[endif]--> CLASE NORMAL package packDistancia. public class Dis_Puntos { private int x1.x1 = x1. int y1. readLine()).println("Distancia entre Dos Puntos"). sum=Math.println("Ingrese dato en X").this. resp=Math.op1. import java. .io.out. int y11 = Integer. System. public static BufferedReader Teclado = new BufferedReader(Leer). this.out.println("ingrese dato en X").out.in).readLine()).pow(op2. } //Creamos un método convencional public double DistanciaPuntos(int x1. System. return resp.println("ingrese dato en Y").op2. public class Principal { public static InputStreamReader Leer = new InputStreamReader(System.println("Ingrese datos del Punto 2"). System.out.y2-this. int y2){ double resp.y1 = y1.2).out.println("Ingrese datos del Punto 1").*. int x11 = Integer.x1. int y1.x2 = x2.2)+Math. op1=this.sum.y2 = y2. op2=this. System.pow(op1.y1.x2-this. public static void main(String[] args)throws IOException { System.out.sqrt(sum). System.parseInt(Teclado.parseInt(Teclado. this. } } CLASE PRINCIPAL package packDistancia. int x2. x22.out.Obtenemos el resultado en Pantalla .DistanciaPuntos(x11.readLine()).y22).y11. Dis_Puntos objpunto = new Dis_Puntos(x11.println(res).println("ingrese dato en Y").-Nos pide ingresar los datos del Punto 2 (Ej.parseInt(Teclado.3)) 2. } } EJECUCIÓN DEL PROGRAMA EN PANTALLA 1..Nos pide ingresar los datos del Punto 1 (Ej. System.int x22 = Integer.readLine())..y22).: P2 (6. System.y11. int y22 = Integer.: P1 (2.7)) 3.out.parseInt(Teclado. double res=objpunto.x22. *. } public int FrenarCarro(int frenar){ this.carro=this. return this.carro=arrancar. } //Creamos métodos Convencionales public int ArrancarCarro(int arrancar){ this. return this.carro.carro-frenar. import java. CLASE NORMAL package pckCarro.carro.carro = carro. public class Principal { . } } CLASE PRINCIPAL package pckCarro.carro+acelerar.carro.carro=this. frenar. acelerar. } public int AcelerarCarro(int acelerar){ this.Programa Nº5 Implementar un programa que realice la función de un Velocímetro marcar la velocidad de un carro al arrancar. public class Velocimetro { private int carro.io. return this. //Creamos un método constructor parametrizado public Velocimetro(int carro) { this. System.readLine()).readLine()).out.println("Velocímetro de un Carro"). arranca=total_velo1.println("Ingrese Velocdidad a Acelerar").ArrancarCarro(arranca).out.out.println(cont_velo+"Km/h. //Proceso de ACELERAR System.println("Carro en estado Apagado").AcelerarCarro(acelera). int resp=Integer.. //Proceso de ARRANQUE System.in). while(cont_velo cont_velo ++. int resp1=Integer.println("Total de Velocidad es:"+ total_velo). .readLine()). System. if(resp==1){ System. int total_velo=objarranca. int cont_velo=0.parseInt(teclado.readLine()).out.out.").parseInt(teclado.out.println("Desea Arrancar [1/0]"). int arranca=Integer.println("Desea Acelerar [1/0]"). while(cont_velo cont_velo ++. } Velocimetro objarranca= new Velocimetro(arranca).parseInt(teclado. System.out. if(resp1==1){ System. int acelera=Integer.println("Ingese Velocidad a Arrancar"). int total_velo1=objarranca..parseInt(teclado. public static void main(String[] args) throws IOException { System. public static BufferedReader teclado=new BufferedReader(leer).public static InputStreamReader leer=new InputStreamReader(System.out. System. while(cont_velo!=arranca){ cont_velo --.readLine()). int frena=Integer.println("Su velocidad Total es:"+ arranca). } //Proceso de FRENAR System.: 5 km/h) . if(resp2==1){ System.out.out.parseInt(teclado. if(frena<=arranca){ int total_velo2=objarranca.println("Ingrese la Velocidad que desea Frenar").Nos pregunta si deseamos arrancar y la velocidad con la que desea arrancar(Ej.FrenarCarro(frena). if(arranca==0) System.out...out.out.println("Lo Sentimos no puede Frenar"). int resp2=Integer.out.out.println(cont_velo+"km/h").println(cont_velo +"km/h. arranca=total_velo2. } System.println("Total de Velocidad es:"+ arranca). } System.out.System. } else System. } } } } EJECUCIÓN DEL PROGRAMA EN PANTALLA 1.println("Vehículo Estacionado").println("Desea Frenar [1/0]").parseInt(teclado.").readLine()). .Banco. } public int SaldoCuenta(int saldo){ . public Transacciones(int cuenta) { this.: 6 km/h) 3.-Luego nos pregunta si deseamos frenar y la velocidad con la que desea frenar (Ej.Luego nos pregunta si deseamos acelerar y la velocidad con la que desea acelerar (Ej.cuenta = cuenta. public class Transacciones { private int cuenta.: 3 km/h) Programa Nº6 Implementar un Programa que permita realizar transacciones de depositar y retirar en una cuenta de banco.2. CLASE NORMAL package pckCta. println("Ingrese el saldo que tiene en su cuenta").cuenta=this. import java.cuenta.println("Ingrese su Numero de Cédula"). return this. System.cuenta. public static void main(String[] args)throws IOException { System.readLine().readLine(). public static BufferedReader teclado=new BufferedReader(leer). .out.println("Cuenta de Banco"). System.out. public class Principal { public static InputStreamReader leer=new InputStreamReader(System. System.out. } public int DepositarCuenta (int depositar){ this. Transacciones objeto = new Transacciones(sal_actual). return this. } public int RetirarCuenta (int retirar){ this.println("Ingrese su Nombre"). return this. String num_cuenta=teclado.Banco.cuenta+depositar.parseInt(teclado. } } CLASE PRINCIPAL package pckCta. System.cuenta-retirar.out. int sal_actual = Integer. String nombre=teclado.cuenta=saldo.println("Ingrese su Número de Cuenta").cuenta=this.*.readLine()).out.io.in).readLine().cuenta. String num_cedula=teclado.this. System. sal_actual=depositar.out. .readLine()).println("Escoja una opción"). System.out.parseInt(teclado. System. sal_actual=retiro.out. System.parseInt(teclado. System.println("'''''''''''Desea Salir presione 3''''''''''''").println("'''''''''''Desea Depositar presione 2''''''''").parseInt(teclado. System.println("***************Cuenta de Banco***************"). int m_depositar=Integer. opcion=Integer.println("ingrese el monto del Deposito").println("Depositar").out.out. System.println("Operación Exitosa"). } break.out.out. switch(opcion){ case 1: System. case 2: System. do{ System.int saldo=objeto. int depositar=objeto.out.readLine()).println("Retiro").out.DepositarCuenta(m_depositar).println("su saldo es "+sal_actual). int m_retiro=Integer.println("'''''''''''Desea Retirar presione 1''''''''''").println("Oeración Exitosa"). int opcion. System.out.RetirarCuenta(m_retiro).readLine()). System.println("Su Saldo Actual es:"+saldo). System.out.println("Ingrese el monto del Retiro").SaldoCuenta(sal_actual).out. if(m_retiro<=sal_actual){ int retiro=objeto.out. .Como parte uno se pide ingresar datos de la persona y número de cuenta. Luego se nos presenta un menú de opciones en el que podemos escoger si queremos depositar. break.println("su saldo es:"+sal_actual). retirar o salir. } } EJECUCIÓN DEL PROGRAMA EN PANTALLA 1...out.Nos pide ingresar el saldo actual de la cuenta.System. } }while(opcion<3). 2. bi++. bi++. } while(bi<30){ vector[bi]=5. } public int[] Conver_Binario(){ int[] vector = new int[30]. public class Num_Conver { private int valor.Programa # 7 Implementar un Programa que permita realizar conversiones de un número decimal a binario.valor>0){ vector[bi]=this.valor/2. this. octal. while(this. } public void setvalor(int valor) { this. } return vector.valor%2.valor = 0.valor = valor.valor=this. CLASE NORMAL package pckConversion. hexadecimal. int bi=0. } public int[] Conver_Octal(){ . public Num_Conver() { this. valor).int[] vector1 = new int[30]. } return vector1. } while(oc<30){ vector1[oc]=5.out.println(respuesta). public static BufferedReader Teclado = new BufferedReader(Leer). } public void Conver_Hexadecimal(){ String respuesta = Integer.valor/8.valor>0){ vector1[oc]=this. public class Principal { public static InputStreamReader Leer = new InputStreamReader(System.io. Num_Conver objeto=new Num_Conver(). } } CLASE PRINCIPAL package pckConversion. while(this.println("Ingrese un numero"). .*. public static void main(String[] args)throws IOException { int[] binario = new int[30]. this.toHexString(this. System. int[] octal = new int[30]. oc++. int oc=0. System.in).valor%8. oc++.valor=this.out. import java. do{ System. }} System.println("'''''''''''' Conversion Hexadecimal presione 3'''''''''''").Conver_Binario().print(binario[i]).println(""). for (int i=19.readLine()).print(octal[i]). case 2: objeto.i>=0.out. System. case 3: objeto. break.int numero=Integer.parseInt(Teclado. System. objeto. .i--){ if (octal[i]!=5){ System.out.readLine()).parseInt(Teclado. switch(opc){ case 1: binario=objeto.setvalor(numero).Conver_Octal(). System. }} System.i>=0.println("el valor en hexadesimal es"). System. System.out. int opc.out.out.out.println(""). break.println("'''''''''''' Conversion Octal presione 2 '''''''''''").out.setvalor(numero).println("'''''''''''' Conversion Binaria presione 1'''''''''''").out.println("*********** Conversion de Nùmeros****************").out. octal=objeto. opc = Integer.i--){ if (binario[i]!=5){ System.println("'''''''''''' Desea Salir presione 4'''''''''''").setvalor(numero).out. for (int i=19. objeto.Conver_Hexadecimal(); break; } }while(opc<4); } } EJECUCIÓN DEL PROGRAMA EN PANTALLA 1.- Nos pide Ingresar un Número y acontinuación nos muestra un menú de opciones: 2.- Al Escoger una opción podemos realizar operaciones como estas: Programa # 8 Implementar un Programa que permita realizar divisiones por medio de Restas. Por Ejemplo: CLASE NORMAL package pckdivisión; public class divi_restas { private int divisor; private int dividendo; public divi_restas(int divisor, int dividendo) { this.divisor = divisor; this.dividendo = dividendo; } public void division_restas(){ int contador=0,cociente=0; do{ cociente=this.divisor-this.dividendo; contador++; divisor=+cociente; }while(cociente>=this.dividendo); System.out.println("Resultado: " +contador); System.out.println("Residuo: " +cociente); } } CLASE PRINCIPAL package pckdivisión; import java.io.*; public class Principal { public static InputStreamReader leer=new InputStreamReader(System.in); public static BufferedReader teclado=new BufferedReader(leer); public static void main(String[] args) throws IOException { System.out.println("Ingrese el Número que va a ser divisor "); int valor1=Integer.parseInt(teclado.readLine()); System.out.println("Ingrese el Número que va a ser dividendo"); int valor2=Integer.parseInt(teclado.readLine()); divi_restas Objeto=new divi_restas(valor1,valor2); Objeto.division_restas(); } } EJECUCIÓN DEL PROGRAMA EN PANTALLA En el programa nos pide ingresar el divisor y el dividendo y a continuación nos muestra el resultado y un residuo si lo hay. RESIDUO DIFERENTE DE CERO RESIDUO IGUAL A CERO Programa # 9 Implementar un Programa que permita resolver potencias por medio de Sumas. Por Ejemplo: CLASE NORMAL package pckpotencia; public class poten_suma { private int base; private int exponente; public poten_suma(int base, int exponente) { this.base = base; this.exponente = exponente; } public void Potencia_Sumas(){ int resultado=1; int numero=1; for(int contador=0;contador int acum=1; while(acum acum++; resultado=numero+resultado; } numero=resultado; } System.out.println("RESULTADO ES:" +resultado); } } CLASE PRINCIPAL package pckpotencia; import java.io.*; public class Principal { public static InputStreamReader leer=new InputStreamReader(System.in); .exponente2). int exponente2= Integer.public static BufferedReader teclado=new BufferedReader(leer).readLine()). int base1= Integer.readLine()).parseInt(teclado.out.Random. import java. CLASE NORMAL package pcktoe_cojuntos. System. public static void main(String[] args) throws IOException { System. poten_suma Objeto=new poten_suma(base1. Objeto.util.println("Ingrese el exponente del Número:").*.println("Ingrese la base del Número:").Potencia_Sumas(). import java. a través de vectores generados mediante valores randómicos.parseInt(teclado. Programa # 10 Implementar un Programa que permita desarrollar la Teoría de Conjuntos en Java.io.in).out. } } EJECUCIÓN DEL PROGRAMA EN PANTALLA En el programa nos pide ingresar la base y el exponente al que deseamos elevar la base ingresada y a continuación nos muestra el resultado. public class conjuntos_toria { public static InputStreamReader leer = new InputStreamReader (System. Random rnd =new Random(). for(int i=0.nextInt(10). numero = rnd. numero = rnd. while(t<5){ int r=0.t=0. } } int o=0. } } if(r==5){ a[t]=numero. t++.i++){ if(this.a[i]!=numero){ r++.b[0]=0.i++){ if(this. public conjuntos_toria() { this.i<5.nextInt(10). for(int i=0. while(o<5){ int r=0. private int [] a=new int [5].b[i]!=numero){ .a[0]=0. private int [] b=new int [5]. } public void LLenar_arrays(){ int numero=0. this.public static BufferedReader teclado = new BufferedReader (leer).i<5. for(int i=0.out.a[h]*this. } } if(r==5){ b[o]=numero. for(int o=0.println("segundo vector ").r++.println(c[h]).o++){ System. for (int h=0.out.h<5.o<5.println(this. o++.b[o]).out.i++){ c[h]+=this.h<5.i<5.} } } public void Mostrar_arrays() throws IOException{ System.a[i]).b[i].out.i<5.println(this. } } public void Teoria_Producto(){ int [] c=new int [5].out. } } . } } for (int h=0.println("primer vector ").i++){ System. } System.h++){ System.h++){ for(int i=0. i<5.println(l[h]).out. l++.h++){ for(int i=0. } } } public void Teoria_Union()throws IOException{ int l=0.h<5. } .h<5.public void Teoria_Iguales()throws IOException{ int []l=new int[10].h++){ for(int i=0.i<5.a[h]==f[i]){ f[i]=11.h<5.b[i]){ l[u]=this. for (int h=0. for (int h=0.i++){ if(this.a[h]==this.a[h].println("Numeros repetidos en los dos vectores").h<10.h++){ f[h]=b[h].out. u++. int u=0.h++){ if(l[h]!=0){ System.i++){ if(this. int []f=new int[5]. for (int h=0. break.} for (int h=0. } } } System. for( i=0. objeto.} } int [] c=new int [10-l]. objeto.LLenar_arrays().println("Teoría de Conjuntos: Producto").println(c[d]). public static BufferedReader teclado = new BufferedReader (leer). for(int m=0.Mostrar_arrays().out. int i.d++){ System.println("Resultado"). } } int v=5. System. import java. objeto.out.d<10-l.*.out. } } } CLASE PRINCIPAL package pcktoe_cojuntos.i<5.m++){ if(f[m]<11){ c[v]=f[m].io.Teoria_Producto().i++){if(i<=5){ c[i]=a[i]. . System. public class Principal { public static InputStreamReader leer = new InputStreamReader (System. public static void main(String[] args) throws IOException { conjuntos_toria objeto = new conjuntos_toria ().}} for(int d=0.m<5.v++.in). out. objeto.out. System.Teoria_Union().println("Resultado").println("Teoría de Conjuntos: Unión").out. objeto. } } .System. System.Teoria_Iguales().out. System.println("Teoría de Conjuntos: Iguales").println("Resultado"). Clase Normal:que es la clase donde vamos a realizar los cálculos correspondientes como son calcular la distancia y Punto Medio. double area = Math.PI * Math.Yo = Yo.Xo).Y1 = Y1.pow(radio. public class Calculos { private int Xo.DistanciaPuntos().this. int X1. this.Y1.Programa #11 Implementar una Función Gráfica en Java que permita dibujar un Círculo y calcular su Área. 2))). return area. } private double DistanciaPuntos() { double d = Math.Y1 . private int X1.this.pow((this. this.sqrt((Math. double radio = distancia / 2.Xo = Xo.X1 = X1. } . 2)) + (Math.Yo. int Y1) { this.pow((this. int Yo. public Calculos(int Xo. 2). return d.X1 .Yo). CODIGO: package appdibujarcirculocalculararea. this. } public double AreaCirculo() { double distancia = this. Y1.Yo. Esta clase se compone de Fuente y Diseño.Xo = Xo. import java. Fuente:que es la parte del código correspondiente a esta clase.} Clase JPanel:que es la clase donde podemos realizar todo tipo de operación gráfica. private int X1.awt.paint(g).awt.*. } public void setYo(int Yo) { this. } public void setY1(int Y1) { this.Graphics. public class Panel extends javax. package appdibujarcirculocalculararea. } @SuppressWarnings("unchecked") @Override public void paint(Graphics g) { super.X1 = X1.Y1 = Y1. import java. public void setX1(int X1) { this. .JPanel { private int Xo.Yo = Yo. } public void setXo(int Xo) { this. } public Panel() { initComponents().swing. setYo(Yo).Y1). Calculos Obj = new Calculos(this.red). double a = Obj.Yo.Y1).JFrame { public Principal() { initComponents().parseInt(this.parseInt(this. int Y1 = Integer. this.X1.texty0.AreaCirculo().parseInt(this.getText()). String cadena = "Area = " + String. int Yo = Integer.event. int X1 = Integer.Xo. package appdibujarcirculocalculararea.texty1.Yo.textX1. Esta clase se compone de Fuente y Diseño.parseInt(this. } @SuppressWarnings("unchecked") private void btngraficarActionPerformed(java. 10.textX0.getText()).getText()).setXo(Xo).awt. . this.g. this.getText()). panel1. this.valueOf(a). public class Principal extends javax. Fuente:que es la parte del código correspondiente a esta clase. g. } public void DibujarCirculo() { repaint().ActionEvent evt) { int Xo = Integer. } } Diseño:que es el lienzo sobre elque realizamos el dibujo Clase JFrame: que es la clase donde podemos realizar la Interfaz Gráfica del Usuario. 15).drawOval(this.Xo. panel1.X1.swing. this. Denominada también clase principal debido que a partir de esta clase ejecutamos el programa.drawString(cadena.setColor(Color. this. g. JLabel jLabel2. private javax.setVisible(true).swing. panel1. private appdibujarcirculocalculararea.swing.JTextField texty1.swing. // End of variables declaration } DISEÑO .JTextField texty0. } // Variables declaration .swing. private javax. private javax.swing.swing. private javax.JTextField textX1.setX1(X1). private javax. private javax. panel1.DibujarCirculo().JLabel jLabel5.swing.JPanel jPanel1.JLabel jLabel4. private javax. } }).swing.JLabel jLabel6.JTextField textX0. private javax.swing.swing.EventQueue.panel1. private javax.awt.JButton btngraficar.setY1(Y1). private javax.swing.JLabel jLabel3. } public static void main(String args[]) { java.Panel panel1.do not modify private javax.JLabel jLabel1. private javax.swing.invokeLater(new Runnable() { public void run() { new Principal(). LIENZO . EJECUCION . . Clase Normal:que es la clase donde vamos a realizar los cálculos correspondientes como son calcular la distancia y Punto Medio. CODIGO: package ejerciciounoproyecto. public class Calculos_Linea { private int X0. private int Y0.Programa # 12 Implementar una Función Gráfica en Java que permita dibujar una Línea y calcular la distancia y Punto Medio. Y1 = Y1.pow((this.Calcular_Distancia().Y0 = Y0.pow((this. double respt=d/2. return res1.X0).X0 = X0. 2))). int Y1) { this. this. 2)) + (Math. } public double Punto_MedioenY(){ double res2=(this.X1 .X1 = X1. Fuente:que es la parte del código correspondiente a esta clase.X0+this. return dis.Y0). .Y0+this.sqrt((Math. return respt. public Calculos_Linea(int X0. } } Clase JPanel:que es la clase donde podemos realizar todo tipo de operación gráfica.X1)/2.Y1 . int Y0. return res2.Y1)/2. } public double Punto_MedioenX(){ double res1=(this. this.this. Esta clase se compone de Fuente y Diseño. private int Y1. } public double Calcular_Distancia(){ double dis = Math. } public double Punto_Medio(){ double d=this. int X1. this.private int X1.this. this. public class Panel extends javax. g.swing.YO = YO.blue).XO = XO.*. g. this. } public void setXO(int XO) { this.drawLine(this. import java. } @SuppressWarnings("unchecked") @Override public void paint(Graphics g) { super. private int X1.awt.awt.XO. private int YO.X1. } public Panel() { initComponents(). import java.JPanel { private int XO. } public void setYO(int YO) { this.this.package ejerciciounoproyecto.Y1 = Y1.Graphics. } public void setY1(int Y1) { this.paint(g).YO. private int Y1. public void setX1(int X1) { this.X1 = X1. .Y1).setColor(Color. g. double resp= obj. this. 10. 60). double resp2=obj.valueOf(resp).drawString(cadena3.Calculos_Linea obj =new Calculos_Linea(this. g. package ejerciciounoproyecto.X1. public class Principal extends javax. double resp3=obj.swing. g.YO.drawString(cadena2. 45).XO.valueOf(resp1). g. Esta clase se compone de Fuente y Diseño. this.Punto_MedioenY(). 30). String cadena = "Distancia es: = " + String.Y1).valueOf(resp3). String cadena2 = "Punto en y = " + String.valueOf(resp2). } } Diseño: que es el lienzo sobre el que realizamos el dibujo.this.JFrame { /** Creates new form Principal */ public Principal() { initComponents().drawString(cadena1. 10.Calcular_Distancia(). 10. 15). String cadena3 = "Punto medio es = " + String. } @SuppressWarnings("unchecked") . String cadena1 = "Punto en x = " + String. Fuente:que es la parte del código correspondiente a esta clase.Punto_MedioenX().Punto_Medio(). Clase JFrame: que es la clase donde podemos realizar la Interfaz Gráfica del Usuario. Denominada también clase principal debido que a partir de esta clase ejecutamos el programa.drawString(cadena. } public void Dibujar_Linea(){ repaint(). 10. double resp1=obj. JLabel jLabel3. panel1.setX1(X1).JLabel jLabel4.ActionEvent evt) { // TODO add your handling code here: } public static void main(String args[]) { java. int YO=Integer.parseInt(this.parseInt(this.awt.invokeLater(new Runnable() { public void run() { new Principal(). private javax.textY1.setY1(Y1).JButton Grafica. panel1.swing.textYO.getText()).Panel panel1. private javax.swing. int X1=Integer. private javax. } private void textY1ActionPerformed(java.JLabel jLabel2. private javax. } // Variables declaration .JLabel jLabel1. panel1.private void GraficaActionPerformed(java. panel1.swing. int Y1=Integer.event.do not modify private javax. private javax. panel1.JPanel jPanel1.parseInt(this.ActionEvent evt) { int XO=Integer.swing.getText()). .event.EventQueue. } }).awt.setYO(YO).swing. private ejerciciounoproyecto.textX1.swing.setXO(XO).awt.parseInt(this.setVisible(true).textX0.getText()).getText()).Dibujar_Linea(). swing. private javax.swing.JTextField textX1.JTextField textYO. private javax. // End of variables declaration } DISEÑO LIENZO .swing.JTextField textY1.JTextField textX0.private javax.swing. private javax. EJECUCION . String Departamento. } . Edad). this.Departamento = Departamento. public Empleado(String Cargo.Cargo = Cargo.. int Edad) { super(Cedula. Nombres.String Cedula. CLASES NORMALES CLASE EMPLEADO public class Empleado extends Persona { private String Cargo. Y como se trata de una herencia contamos con varias clases normales y una principal. this. private String Departamento. String Nombres.Programa # 13 Implementar un programa de Herencia. private String Especialidad. Nombres. String Semestre.Departamento). public void setEspecialidad(String Especialidad) { this. Edad).DatosInformativos().out. String cadSueldo = " Sueldo: " + String. } @Override public void DatosInformativos() { . } public Estudiante(String Colegio.println("Departamento: " + this. int Edad) { super(Cedula. System.Especialidad = Especialidad. String Nombres. double valorHora) { double sueldo = numHoras * valorHora.println("Cargo: " + this. this.out.Semestre = Semestre. } public String CalcularSueldo(int numHoras. } } CLASE ESTUDIANTE public class Estudiante extends Persona { private String Colegio. private String Semestre. String Cedula.Cargo). System.valueOf(sueldo). this. return cadSueldo.@Override public void DatosInformativos() { super.Colegio = Colegio. out...println("Nombres: " + this. System.Edad = Edad. this.out.Cedula = Cedula. .println("Colegio: " + this.println("Creando Objeto Empleado. System.out.. System.Nombres = Nombres.Cedula).Semestre). public Persona(String Cedula. } } CLASE PRINCIPAL public class Principal { public static void main(String[] args) { System. this.!").out. String Nombres. System.out.println("Cedula Identidad: " + this.out.println("Semestre: " + this. } } CLASE PERSONA public class Persona { private String Cedula.println("Edad: " + this. private String Nombres.Edad). } public void DatosInformativos() { System. int Edad) { this.Especialidad).super. System.println("Especialidad: " + this.out.Nombres).Colegio). private int Edad.DatosInformativos(). DatosInformativos().CalcularSueldo(60. int Edad Estudiante Pedro = new Estudiante("Monterrey"."12034576891". "Sistemas".setEspecialidad("Telecomunicacion"). Juan. 15).println(Juan.. } } PROGRAMACION EN NETBEANS JAVA JAVA NETBEANS Java es un lenguaje de programación orientado a objetos que comparte gran parte de su sintaxis con C y C++.!"). int Edad Empleado Juan = new Empleado("Director". sus creadores Sun Microsystems. String Departamento."1207895431".out. StriSng Nombres. . String Cedula.long Cedula. String Nombres.."Mariuxi Lopez". //String Colegio. Java es uno de los lenguajes más poderosos que existe.println("Creando Objeto Estudiante.DatosInformativos(). String Semestre. Pedro.. System.out.35).//String Cargo."Carlos Torres"."Octavo".18)). Pedro. System. Las clases tienen atributos y métodos. etiquetas. . Las clases son el fundamento de la programación orientada a objetos y podríamos decir que son el molde con el que hacemos nuevos objetos. En el código que se genera automaticamente por NetBeans tenemos dos métodos. Y se compone de paquetes dentro de los cuales hay clases las que contienen atributos y métodos. el método Main() que también se conoce como el constructor de la clase y el método main() que es el punto de inicio del programa (por las mayúsculas y minúsculas Main es diferente de main). Los atributos son lo que nos dice cómo es esa clase. Esto quiere decir que integra todas las herramientas que necesitamos para poder desarrollar. La utilización del entorno de NetBeans es sencilla. los atributos de una persona son el color de ojos y el alto (entre muchos otros). por ejemplo correr.etc. también se manejan objetos.NetBeans es un entorno de desarrollo integrado (IDE por sus siglas en inglés). por ejemplo. ENTORNO GRAFICO DE NETBEANS El entorno Grafico de netbeans maneja dos tipos de clases: Formulario/jframe: agrega objetos.botones. los métodos son las acciones que puede realizar una clase. parseInt(this. panel1. panel1. panel1. int Y1 = Integer.JFrame { public Principal() { initComponents().awt.parseInt(this.setYo(Yo).ActionEvent evt) { int Xo = Integer. } private void textX0ActionPerformed(java.parseInt(this.getText()).event.awt.textX0. area de dibujo.getText()). int Yo = Integer. int X1 = Integer. panel1. } @SuppressWarnings("unchecked") Generate codigo private void btngraficarActionPerformed(java.DibujarCirculo().setY1(Y1).texty1.textX1. Codigo jFrame package appdibujarcirculocalculararea.parseInt(this.setX1(X1).awt. public class Principal extends javax. .ActionEvent evt) { // TODO add your handling code here: } public static void main(String args[]) { java.getText()).Lienzo/jpanel: Operaciones.EventQueue.swing.setXo(Xo). Para compilar los programas se hace click en el botón correr EJERCICIO Programa que realiza el cálculo del área de un círculo y la longitud del mismo mediante el programa Netbeans de Java.event.invokeLater(new Runnable() { .getText()).texty0. panel1. swing. import java.JPanel { private int Xo. private javax. import java.JTextField texty1.JButton btngraficar.swing.Yo.swing.swing.swing. private javax. public class Panel extends javax. // End of variables declaration } //Lo que se realice en el jFrame es el diseño del formulario y la utilización de cada uno de los label para las escrituras de las cantidades necesarias para el programa.JLabel jLabel5.JTextField texty0.*. private appdibujarcirculocalculararea. private javax.JLabel jLabel1. private javax. private javax.swing. private javax.swing.awt. .Panel panel1.setVisible(true).JPanel jPanel1.do not modify private javax.JLabel jLabel2.JLabel jLabel4. private javax.JTextField textX0.swing. } // Variables declaration .swing. private int X1.swing.Graphics. private javax. y llamar al método que grafica el circulo.Y1. private javax.swing.JLabel jLabel3.awt.// Codigo jPanel package appdibujarcirculocalculararea. } }). private javax.public void run() { new Principal().JTextField textX1.swing. Xo. this. } @SuppressWarnings("unchecked") Generate codigo @Override public void paint(Graphics g) { super. g. } public void setY1(int Y1) { this.BLUE).drawString(cadena.valueOf(a). double b = Obj.setColor(Color. . g.public void setX1(int X1) { this.X1.X1 = X1. 10.DARK_GRAY). g.setColor(Color. this. this.Yo = Yo.Xo. double a = Obj.MAGENTA).Y1 = Y1. this.Y1). g.drawOval(this.Xo = Xo.Yo.setColor(Color. g. String cadena = "Area = " + String. } public Panel() { initComponents().Yo. } public void setXo(int Xo) { this.Y1).Longitud(). this. Calculos Obj = new Calculos(this. this. 15). } public void setYo(int Yo) { this.AreaCirculo().paint(g).X1. pow((this. g.pow((this.drawString(cad. private int X1. int Yo. 2)) + (Math.Yo.Xo). } private double DistanciaPuntos() { double d = Math.Y1 . 2))). this. this.Xo = Xo. this.Y1)”. public Calculos(int Xo.String cad = "Longitud = " + String. this. } public double AreaCirculo() .Y1.X1 = X1.Y1 = Y1.valueOf(b).Xo.Yo = Yo. int X1. this. } public void DibujarCirculo() { repaint(). this.this. asi mismo el presentar en pantalla elos mensaje del area y la longitud Codigo Calculo package appdibujarcirculocalculararea. return d.do not modify // End of variables declaration } //En el JPanel se realiza el dibujo del circulo con la función determinada para hacer el grafico “ g.Yo. public class Calculos { private int Xo.sqrt((Math.this. } // Variables declaration .drawOval(this.X1 . 10. 25). int Y1) { this.X1.Yo). double radio = distancia / 2. double radio = distancia / 2.PI*radio.DistanciaPuntos(). } } //Se realizan los calculos respectivos para los el area y la longitud. return area.DistanciaPuntos(). double area = Math.{ double distancia = this. return longi. VISTA PREVIA ANTES DE LA EJECUCION .PI * Math. 2). lascuales llamaremos luego el JPanel.pow(radio. } public double Longitud() { double distancia = this. double longi=2*Math. EJECUCION DEL PROGRAMA 3333333333333333333333333333333333333333333333333333333333333333333333333333333 EJEMPLOS JAVA NETBEANS 1. realizar un programa en java netbeans que pida un digito y lo valla sumando y muestre el resultado este operación debe realizarse hasta que el usuario digite el numero 25 . import javax. Realizar un programa en java netbeans que pida 3 digito al usuario. n=Integer. en el cual debe encontrar el número del centro. if (n==25){ c=2.swing."la sumatoria es "+s. package ejercicio.JOptionPane. s=s+n. choose Tools | Templates * and open the template in the editor.JOptionPane. * @author public class Ejercicio1 { @param args the command line arguments public static void main(String[] args) { . while (c==1){ a=JOptionPane.pkg1. public class Ejercicio1 { public static void main(String[] args) { String a."".s=0.parseInt(a) .JOptionPane. import javax.swing. ) .. package ejercicio. int n. * To change this template. } } } 2.pkg1.c=1. Debe dejar de pedir número al usuario y realizar esta operación hasta que la suma total de los tres digito sea igual a 15.showMessageDialog(null.showInputDialog("digite un numero".PLAIN_MESSAGE) . } JOptionPane. if (suma==15){ con=2. ) .n2.JOptionPane.showMessageDialog(null. ) . ."el numero del centro es"+n2."el numero del centro es"+n3. } else if(n2>n1&&n2<n3||n2<n1&&n2>n3){ JOptionPane.con=1. sea mayor a 10.parseInt(a) .n3.b. } else{ if(n1>n2&&n1<n3||n1<n2&&n1>n3){ JOptionPane.showMessageDialog(null."".PLAIN_MESSAGE) .showInputDialog("digite #2".ERROR_MESSAGE) .c. Realizar un programa en java netbeans en el cual debe pedir 3 dígitos al usuario. Hallar el Máximo común Divisor.PLAIN_MESSAGE) .PLAIN_MESSAGE).JOptionPane. n1=Integer. } else if(n3>n2&&n3<n1||n3<n2&&n3>n1){ JOptionPane."".D.showInputDialog("digite #3"."el numero del centro es"+n1.parseInt(c) . if (n1==n2||n2==n3||n3==n1) { JOptionPane. n3=Integer.showMessageDialog(null. } } suma=n1+n2+n3. } } } } 3. c=JOptionPane. ) .JOptionPane.showInputDialog("digite #1".String a. b=JOptionPane."". int n1."".showMessageDialog(null. package javaapplication13.parseInt(b) .JOptionPane. while (con==1){ a=JOptionPane. n2=Integer. este programa debe cerrarse hasta el M. C.suma."Hay un numero repetido no se puede hallar el del centro". Realizar un programa en java netbeans en el cual pueda hallar el área de: . num3=JOptionPane. x++){ if(n1 % x == 0 & n2 % x == 0 & n3 % x == 0){ mcd=x.n2.num3. x<=a. n3=Integer. n1=Integer. } else if (n2<n1&&n2<n3){ a=n2.parseInt(num1) .d es "+mcd) .con=0.c.num2.showInputDialog(" ingrese el segundo numero" ) ."m. while (con==0){ num1=JOptionPane. if(n1<2&&n1<n3) { a=n1.showInputDialog(" ingrese primer numero" ) . @author Administrador public class JavaApplication13 { * @param args the command line arguments public static void main(String[] args) { String num1. } else { a=n3. num2=JOptionPane.a. } for(int x=1.parseInt(num2) .showInputDialog(" ingrese tercer numero" ) . mcd=0.showMessageDialog(null.import javax.parseInt(num3) .n3. if(mcd>10){ con=1. int n1.JOptionPane. n2=Integer. } } JOptionPane.swing. } } } } 4. do{ num1=JOptionPane. * @author Administrador public class JavaApplication5 { * @param args the command line arguments public static void main(String[] args) { String num1.showInputDialog("ingrese base". a= Integer. resp=b*b.JOptionPane.parseFloat(num2) . package javaapplication5. b= Float. import javax. .num2.showInputDialog("ELEJIR ARIA A REALIZAR n1 area al cuadradon2 area del triangulon3 area del rectangulon4 area del circulon5 SALIR " ."area del cuadrado "+ resp.PLAIN_MESSAGE). case 2: num2=JOptionPane. float b.swing. b= Float. ) . switch (a){ case 1: num2=JOptionPane."Resultado". ) .parseInt(num1).showMessageDialog(null.resp. choose Tools | Templates * and open the template in the editor. ) .parseFloat(num2) .break. JOptionPane.c.num3. int a.cont=1.showInputDialog("ingrese primer lado ".JOptionPane.a/ área al cuadrado b/ área del triangulo c/área rectángulo d/área circulo salir * To change this template. parseFloat(num3) . JOptionPane.PLAIN_MESSAGE) .JOptionPane. } } while(cont==1) ."Resultado".showMessageDialog(null.showInputDialog("ingrese Altura".JOptionPane."ERROR"."area del Circulo "+ resp. ) ."area del Rectangulo "+ resp. } } 5.break.showInputDialog("ingrese base". JOptionPane.JOptionPane. case 3: num2=JOptionPane. c= Float.PLAIN_MESSAGE) .break.PLAIN_MESSAGE).num3=JOptionPane.2) .showInputDialog("ingrese Altura". JOptionPane.showMessageDialog(null.ERROR_MESSAGE) . ) . c= Float.parseFloat(num2) ."Numero no Valido ". ) ."salir ".showInputDialog("ingrese Radio".JOptionPane. default: JOptionPane.parseFloat(num3) . num3=JOptionPane."Resultado".pow(b. b= Float. Realizar un programa en netbeans el cual el programa de dos numero . resp= b*c."salir".parseFloat(num2) .PI * (float) Math.PLAIN_MESSAGE) . resp=(b*c)/2 ."area del Triangulo "+ resp. case 5: cont = cont + 1."Resultado".showMessageDialog(null. resp = (float) Math.showMessageDialog(null. ) . b= Float.JOptionPane. JOptionPane.showMessageDialog(null.break.break. case 4: num2=JOptionPane. n1=0.showMessageDialog(null. res1.showMessageDialog(null.sqrt(res). import javax. public class Ejerciciosenclase { public static void main(String[] args) { //comienzan los codigos int x=0.random() * 20). package ejerciciosenclase. raíz cuadrada de la suma de los dos dígitos .random() * 20).//aqui se hace el numero elevado JOptionPane. res=0. p1=0. n2=0. JOptionPane. JOptionPane.max(n1. n2) . //aqui se le da valor random a la variable p= (int) Math. ) ."Mayor = "+p1) . res2=0.min(n1.showMessageDialog(null.showMessageDialog(null.//aqui se ase la suma de los números random res1= (int) Math.showMessageDialog(null. //aqui se le da valor random a la variable n2= (int) Math. } } } } 4444444444444444444444444444444444444444444444444444444444444444444444444444444 44 ."Menor = "+p) .ceil(Math. p=0.ceil(Math.pow(n1. //aqui se muestran los resultados obtenidos JOptionPane. if(res1>4){ //aqui se hace la toma de desiciones para cerrar el programa x=1. diga cual es el mayor y cual es el menor de los dígitos dado por el programa a lazar. //aqui encuentro el número mayor JOptionPane.//aqui se muestran los resultados obtenidos JOptionPane. n2) . la suma total de eso dos dígitos .JOptionPane."Número elevado = "+res2) .swing. res=n1+n2. //aqui encuentro el número menor p1= (int) Math. while(x==0){ n1= (int) Math.showMessageDialog(null."Programa se va a cerrar"."Raiz cuadrada de "+res+" es = "+res1) . a^b .//aqui se saca la raiz cuadrada de la suma de los numeros random res2= (int) Math. JOptionPane. este programa debe cerrarse hasta que el resultado de la raíz sea mayor a 4."Segundo random = "+n2) . n2).cualquiera.showMessageDialog(null."Primer random = "+n1) . guardar. que es un tema fundamental en cualquier lenguaje de programación.portalhacker. Para ello tendremos las siguientes clases: Archivo. y Java no es la excepción. será muy probable y práctico pues el acceso directo a ficheros OK. Se hace importante porque nos permite interactuar con los dispositivos de almacenamiento externo para poder mantener la información en el tiempo. Hola amigos y amigas hoy les muestro alguito mira. pues uno de los temas es el manejo de archivos es decir la Persistencia.0 Manejo de Archivos en Java. es por eso que muchos usuarios configuran sus navegadores para permitir el acceso al sistema de ficheros. guardar cómo y por consiguiente que tenga las opciones de abrir y salir. cuando estamos cursando la materia de introducción a la programación o introducción a la Informática. . Recuperar(). Escribir(Object A). cuando se desarrollan applets para utilizar en red. Leer().http://www. Lo que haremos es. pero otros lamentablemente no realizan esta acción. crear una aplicación usando archivos serializados para almacenar contactos que pretenda la administración y gestión de agenda personal con las opciones de: Nuevo registro.php?topic=60805. Salvar(Objects A). ObjectImputStream entrada. Mira ahora te comento algo. diciendo primero que si se está desarrollando una aplicación JAVA para nuestro uso interno. Bueno sin más palabras hagamos una aplicación de esto.java={File fila. Muchos lenguajes nos permiten manejar Archivos. Es decir volver a ejecutar el programa que hicimos después de un tiempo y recuperando la información. hay que tener en cuenta que la entrada/salida directa a fichero es una violación de seguridad de acceso. ObjetOuputStream salida} Metodos Archivo: Archivo().net/index. GetPersonas(). Guardar(File f). Personas. Persona>} Metodos Personas: Personas(). Gets() y Sets(). Es decir el Form de Bienvenida verifica la contraseña del usuario. String Dni.AdicionarPersona(Persona p). Y finalmente hacemos una clase Form de Bienvenida y el otro Form del Contenedor Principal. String ape…. String Apellido. SetPersonas().Persona. Integer Edad. de ser correcta hace visible al Form Contenedor. String Direccion} Metodos Persona: Persona().java={HashMap<String. Cargar(). La corrida del programa es asi: . Persona(String nom. Integer celular.).java={String nombre. . com el programa se trata de un menu de manejo de archivos de un txt que hace las operaciones o funciones de: ****crea el . El ejecutable Descargalo Aqui.java para netbeans o cualquier lenguaje de programacion de java y ademas es de Angel Wha su servidor ahi lo modifican y lo analizan saludos OwO!!! cualquier duda mi correo es: [email protected] por default cuando agregas un registro***** . Dejar Comentarios Click Aqui 55555555555555555555555555555555555555555555555555555 pues aqui dejo un pequeño codigo . .La contraseña es “william” El proyecto en Netbeans podras Descargarlo Aqui. import java. operaciones(). public class Manejo_Archivos_Proyecto {static Empleados lista = null.*.txt"). //si la lista sufre cambios se escribe en el discoASWS static boolean cambios. . } public static void leer() { ObjectInputStream ois = null.io. public static void main(String[] args) { leer().3565 Código Fuente: ****1***** package manejo_archivos_proyecto. escribir(). try { /* Creaci&#65533.n considera dos casos si el archivo existe previamente o no */ File fichero = new File("empresa.net/codigos/java/menus/menu_manejo_de_archivos_en_java_netbeans.1-agregar 2-eliminar 3-modifica 4-busca 5-sale del menu o del registros registros registros registros programa saludos este es el programa que andube buscando en internet hace mucho pero no mas no asi que lo hice en equipo con mas compañeros y salio y aqui mas facil para que no batallen asiendolo y de aqui se guien saludos OwO!!! URL: http://mygnet. // short edad = 0. .out. } } catch (ClassNotFoundException e) { System.println("Archivo Nuevo"). int nihss.in).out.println("Ya existe").out.exists()) { lista = new Empleados().toString()).println("Error: " + e. int codigo = 0. } catch (IOException e) { System. lista = (Empleados) ois. String nombre. BufferedReader br = new BufferedReader(isr).close().out. System. InputStreamReader isr = new InputStreamReader(System.println("Error: " + e. } finally { try { if (ois != null) { ois. } else { ois = new ObjectInputStream(new FileInputStream("C:UsersAngel WhaDocumentsNetBeansProjectsManejo_Archivos_Proyectosrcmanejo_archivos_pr oyectoempresa.txt")). System.if (!fichero.toString()). int posi = -1. } } catch (IOException e) { } } } public static void operaciones() { short opcion = 0. apellido = null.readObject(). out. "). System. Ver registros").readLine()).parseShort(new BufferedReader( new InputStreamReader(System.in)).out. // Mantenimiento try { do { System.println(). System.out.readLine()). switch (opcion) { /////////////////////////////////////////////////// /* Agregar Registros */ case 1: do { error = false.out. Salir del Programa"). } catch (NumberFormatException ne) { System. .out.println("MENu"). } while (opcion < 1 || opcion > 4).println("3. System.print("Tu opcion fue--> do { opcion = Short.println("2.boolean eliminado = false. Agregar Registros"). boolean error. Eliminar Registros").print("Ingresa su ID: "). System.parseInt(br. System.println("1.out.println("4.out.out. System. try { System.println("Error*** valor incorrecto" + " (Solo numeros)").out. codigo = Integer. out.readLine(). break. apellido. nihss)). "). } } while (error).out.readLine()).parseInt(br.agregar(new Empleado(codigo. //////////////////////////////////// /* case 2: do { error = false. } catch (NumberFormatException ne) { System. } } while (error).out.print("Apellidos: apellido = br. do { error = false.error = true.println("Error***" + " (Solo Numeros)").parseShort(br.out.print("Id del Registro ma Borrar: "). error = true.print("Nombres: nombre = br.println("Error*****" + " (Solo Numeros)").print("Matricula: "). codigo = Short. try { System.readLine(). nihss = Integer. System.readLine()). "). try { System. lista. } catch (NumberFormatException ne) { System. System. cambios = true. Eliminar registros */ .out. nombre.out. try { System. } else { System.readLine()).println("Error*****" + " (Solo Numeros)").println("No se Encuentra").out. } catch (NumberFormatException ne) { System.parseShort(br.print("Ingrese el ID para Buscar"). error = true.out.out.out. } else if (lista. eliminado = lista. if (eliminado) { System. } break.println("Archivo vacio").longitud() != 0) { . /////////////////////////////////////////// /* Ver registros */ case 3: do { error = false.println("Registro eliminado del archivo"). } } while (error). codigo = Short.out. if (posi == -1) { if (lista.buscar(codigo).error = true. posi = lista. } } while (error).eliminar(codigo).longitud() != 0) { System. cambios = true. } else { System.elemento(posi). try { if (cambios) { ous = new ObjectOutputStream(new FileOutputStream("empresa.txt")). .System. ous.out.out. } catch (IOException e) { } } ///////////////////////////////////////// /* Funciones*/ public static void escribir() { ObjectOutputStream ous = null.println("Archivo vacio"). } } else { lista.println("Error: " + e.out. } break. /////////////////////////////////////////////// /*Salir*/ case 4: } } while (opcion != 4).println("No se Encuentra").toString()).mostrar(). } catch (IOException e) { System.writeObject(lista). } lista = null. close().io. private Empleado[] empleados. public Empleados() { // Crea el array nElementos = 0.} finally { try { if (ous != null) { ous. import java. } } catch (IOException e) { } } } } ****2***** package manejo_archivos_proyecto. private int nElementos.Serializable. public class Empleados implements Serializable { private static final long serialVersionUID = 1L. empleados = inicializar(nElementos). } . for (int i = 0.println("No hay elementos en esa posici&#65533. } } public int longitud() { return empleados. i < nElementos.length.out. } else { System.length.out. empleados = inicializar(nElementos + 1).toString()). } public void agregar(Empleado unEmpleado) { Empleado[] copiaDeLista. nElementos = copiaDeLista. return empleados. i++) { empleados[i] = copiaDeLista[i]. } } public Empleado elemento(int i) { if (i >= 0 && i < nElementos) { return empleados[i]. //el array crece conforme se le van anadiendo nuevos elementos copiaDeLista = empleados. .n").println(e. } catch (OutOfMemoryError e) { System. } empleados[nElementos] = unEmpleado. return null.private Empleado[] inicializar(int nElementos) { try { return new Empleado[nElementos]. } } nElementos--. for (int i = 0. copiaDeLista = empleados. empleados = inicializar(nElementos .length != 0) { nElementos = copiaDeLista. } } return posi. i++) { if (copiaDeLista[i] != null) { empleados[i] = copiaDeLista[i]. if (copiaDeLista. i < nElementos. return true. int posi = buscar(cod).getCodigoEmpleado() == cod) { posi = i. if (posi != -1) { // el array disminuye cuando se eliminan elementos empleados[posi] = null. for (int i = 0. } } return false.1).length.nElementos++. i < nElementos. } public boolean eliminar(int cod) { Empleado[] copiaDeLista. i++) { if (empleados[i]. } public int buscar(int cod) { int posi = -1. } . int nihss) { super(). Nombre = nombre. String Nombre. String Apellido.} ****3**** /* * To change this template. */ package manejo_archivos_proyecto. } public Empleado() { super(). Nihss = nihss. } public String getApellido() { return Apellido. } . public class Empleado implements java. choose Tools | Templates * and open the template in the editor. String nombre. CodigoEmpleado = codigoEmpleado. String apellido. public Empleado(int codigoEmpleado. int Nihss.Serializable { int CodigoEmpleado.io. Apellido = apellido. } public int getNihss() { return Nihss. .getCodigoEmpleado()).getNombre()). System.println(this. } public int getCodigoEmpleado() { return CodigoEmpleado. } public void setNombre(String nombre) { Nombre = nombre. } public void setCodigoEmpleado(int codigoEmpleado) { CodigoEmpleado = codigoEmpleado.println(this. } public void setNihss(int nihss) { Nihss = nihss. } public String getNombre() { return Nombre.getApellido()).public void setApellido(String apellido) { Apellido = apellido.println(this.out.println(this.getNihss()).out. } public void mostrar() { System. System.out.out. System. } //public abstract double CalcularIngreo(). } .
Copyright © 2024 DOKUMEN.SITE Inc.