+ All Categories
Home > Documents > Ejemplos de Programacion en Java William Loor

Ejemplos de Programacion en Java William Loor

Date post: 14-Sep-2014
Category:
Upload: ricardo-rivadeneira
View: 485 times
Download: 2 times
Share this document with a friend
Popular Tags:
96
UNIVERSIDAD LAICA “ELOY ALFARO DE MANABÍ ” EJEMPLOS REALIZADOS EN L.P.O.O JAVA PROGRAMACIÓN AVANZADA Tutor: Ricardo Rivadeneira Paralelo: 5 to “A” Ing. De Sistemas.
Transcript
Page 1: Ejemplos de Programacion en Java William Loor

UNIVERSIDAD LAICA “ELOY ALFARO DE

MANABÍ ”

EJEMPLOS REALIZADOS EN L.P.O.O JAVA

PROGRAMACIÓN AVANZADA

Tutor: Ricardo Rivadeneira

Paralelo: 5 to “A” Ing. De Sistemas.

Page 2: Ejemplos de Programacion en Java William Loor

NETBEANS –JAVA APPLICATION COMO INGRESAR TEXTO Y NUMEROS

public static void main(String[] args) {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

try

{

System.out.println ("un valor");

int a = Integer.parseInt(br.readLine());

System.out.println ("un mensaje");

String txt = br.readLine();

System.out.println("El Valor es : "+ 9 +" El Mensaje "+ txt);

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

INGRESAR NÙMEROS Y LETRAS public static void main(String[] args) {

InputStreamReader isa = new InputStreamReader(System.in);

BufferedReader b = new BufferedReader (isa);

try

{

System.out.println("Ingrese un valor: ");

int ba = Integer.parseInt(b.readLine());

System.out.println("Ingrese un Mensaje: ");

String Txt = b.readLine();

System.out.println("El Valor es: "+9 +" El Mensaja"+Txt);

}

catch(Exception e)

{

e.printStackTrace();

}

}

}

Page 3: Ejemplos de Programacion en Java William Loor

NÚMERO MAYOR

public static void main(String[] args) {

// TODO code application logic here

InputStreamReader sr=new InputStreamReader (System.in);

BufferedReader b=new BufferedReader (sr);

try

{

System.out.println("Ingrese 1 valor numerico");

int N1 =Integer.parseInt(b.readLine());

System.out.println("Ingrese 2 valor numerico");

int N2 =Integer.parseInt(b.readLine());

System.out.println("Ingrese 3 valor numerico");

int N3 =Integer.parseInt(b.readLine());

if (N1> N2 & N1>N3)

{

System.out.println("El Numero mayor es ;" +N1);

}

else

{

if (N2> N1 && N2>N3)

{

System.out.println("El Numero mayor es ;" +N2);

}

else

{

System.out.println( "El Numero mayor es ;" +N3);

}

}

}

catch (Exception e)

{

e.printStackTrace ();

}

}

}

Page 4: Ejemplos de Programacion en Java William Loor

OPERACIONES MATEMÁTICAS SIMPLES public static void main(String[] args) {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

try

{

System.out.println ("Primer valor");

int a = Integer.parseInt(br.readLine());

System.out.println ("Segundo valor");

int b = Integer.parseInt(br.readLine());

int suma = a + b;

int Rest = a - b;

int Mult = a * b;

int Div = a / b;

System.out.println("La Suma es : "+ suma);

System.out.println("La Resta es : "+ Rest);

System.out.println("La Multiplicacion es : "+ Mult);

System.out.println("La Division es : "+ Div);

} catch (Exception e) {

e.printStackTrace(); }

INVERTIR CARACTERES public static void main(String[] args) {

InputStreamReader isr=new InputStreamReader(System.in) ;

BufferedReader br=new BufferedReader(isr);

try {

System.out.println("ingrese frase");

String texto=br.readLine();

int d=texto.length();

String a="";

for(int i=d-1; i>=0; i--){

a=a+texto.charAt(i);

}

System.out.println(a);

} catch (Exception e) {

e.printStackTrace();

} }}

Page 5: Ejemplos de Programacion en Java William Loor

OPERACIONES MATEMÁTICAS CON FUNCIONES public static void main(String[] args) {

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

try {

System.out.println("ingrese primer valor");

int vl= Integer.parseInt(br.readLine());

System.out.println("ingrese segundo valor");

int vl1= Integer.parseInt(br.readLine());

operacionesconFuncioness e=new operacionesconFuncioness();

int valor=e.suma(vl, vl1);

System.out.println("la suma es:"+valor);

int valor1=e.resta(vl, vl1);

System.out.println("la resta es:"+valor1);

int valor2=e.multiplicacion(vl, vl1);

System.out.println("la multiplicacion es:"+valor2);

int valor3 = e.divicion(vl, vl1);

System.out.println("la division es:"+valor3);

} catch (Exception e) {

} }

public int suma(int a,int b) {

int r;

r=a+b;

return r; }

public int resta(int a,int b) {

int h;

h=a-b;

return h; }

public int multiplicacion(int a,int b) {

int r;

r=a*b;

return r; }

public int division(int a,int b) {

int r;

r=a/b;

return r; }

}

Page 6: Ejemplos de Programacion en Java William Loor

CONTAR PARES E IMPARES public static void main(String[] args) {

InputStreamReader sr = new InputStreamReader(System.in);

BufferedReader b = new BufferedReader(sr);

try{

System.out.println("Ingrese una cadena de Caracteres");

String texto = b.readLine();

paresimpares sm = new paresimpares();

String a = sm.par(texto);

String a1 = sm.impar(texto);

System.out.println("Pares: " + a );

System.out.println("Promedio de pares: " + a.length());

System.out.println("Impares: " + a1);

System.out.println("Promedio de Impares: " + a1.length());

} catch(Exception e) {

e.printStackTrace(); } }

public String par(String cadpar) {

int acu=0;

String txt = "";

int lg = cadpar.length();

lg -=1;

int i, r;

for(i=0; i<=lg; i++) {

r= (i+1) % 2;

if (r==0) {

txt += cadpar.charAt(i);

acu = acu + 1;

} } return (txt); }

public String impar(String cadimp) {

int acu1=0;

String txt = "";

int imp = cadimp.length();

imp -= 1;

int i, r;

for(i=0; i<= imp ; i++) {

r=(i+1) % 2;

if (r==1) {

txt += cadimp.charAt(i);

acu1=imp + imp;

} } return (txt); } }

Page 7: Ejemplos de Programacion en Java William Loor

VALIDAR CÉDULA(con array) private static String ncedula;

public static void main(String[] args) {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

Scanner entrada = new Scanner(System.in);

try {

System.out.println("Ingrese el numero de cedula");

ncedula = entrada.next();

int cedula[] = new int[ncedula.length()];

int res = 0;

if (cedula.length == 10) {

for (int i=0; i<cedula.length ; i++) {

cedula[i]=Integer.parseInt(String.valueOf(ncedula.charAt(i) ));

int r = i%2;

if (r==0) {

cedula[i]= cedula[i]* 2;

if (cedula[i]>9)

cedula[i]= cedula[i]-9;

}

}

for (int i=0; i<cedula.length -1; i++) {

res = res + cedula[i];

}

res = res%10;

if (res!=0)

res = 10-res;

if (res == cedula[9])

System.out.println("CEDULA VALIDA");

else

System.out.println("CEDULA INVALIDA");

} else {

System.out.println("CEDULA INVALIDA");

}

} catch (Exception e) {

{ e.printStackTrace();

}

}

}

}

Page 8: Ejemplos de Programacion en Java William Loor

VALIDAR CÉDULA public static void main(String[] arg) {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

try {

System.out.println("Ingrese el número de cédula: ");

String nc = br.readLine();

int lg = nc.length();

int t;

if (lg == 10) {

int si = 0, sp = 0;

for (int i = 0; i < lg - 1; i++) {

int d = Integer.parseInt("" + nc.charAt(i));

if ((i + 1) % 2 == 0) {

sp = sp + d;

} else {

d = d * 2;

if (d > 9) {

d = d - 9;

}

si = si + d;

}

}

t = si + sp;

t = t % 10;

int k = Integer.parseInt("" + nc.charAt(lg - 1));

t=t+k;

if ((t % 10)==0) {

System.out.println("Cédula correcta");

} else {

System.out.println("Cédula incorrecta");

}

}

} catch (Exception e) {

}

}

}

Page 9: Ejemplos de Programacion en Java William Loor

GENERAR LOS NUMEROS DE " A hasta B " CON FOR

public static void main(String[] args) {

InputStreamReader sr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(sr);

try {

System.out.println("Ingrese Valor para A");

int A = Integer.parseInt(br.readLine());

System.out.println("Ingrese Valor para B");

int B =Integer.parseInt(br.readLine());

int i=A;

int r=0;

if (A>B)

{

for (i=A; i>=B; i--)

{

r=i;

System.out.println(i );

}

}

else

{

for (i=A; i<=B; i++)

{

r=i;

System.out.println(i);

}

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

Page 10: Ejemplos de Programacion en Java William Loor

GENERAR LOS NUMEROS DE " A hasta B " CON

WHILE public static void main(String[] args) {

InputStreamReader isr= new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

try {

System.out.println("INGRESE VALOR DE A");

String a=br.readLine();

System.out.println("INGRESE VALOR DE B");

String b=br.readLine();

int u= Integer.parseInt(a);

int l= Integer.parseInt(b);

if(u==l){

System.out.println("error");

}

else

{

if (u>0 && u>l){

int i=u;

while (i>=l) {

System.out.println(i);

i--;

}

} else {

int i=u;

while (i<=l) {

System.out.println(i);

i++;

}

}

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

Page 11: Ejemplos de Programacion en Java William Loor

GENERAR LAS TABLAS DE MULTIPLICAR CON FOR public static void main(String[] args) {

InputStreamReader N=new InputStreamReader(System.in);

BufferedReader b=new BufferedReader (N);

InputStreamReader sr1=new InputStreamReader (System.in);

BufferedReader V1=new BufferedReader (sr1);

InputStreamReader sr2=new InputStreamReader (System.in);

BufferedReader V2=new BufferedReader (sr2);

try {

System.out.println("INGRESE EL NUMERO DE LA TABLA");

int n =Integer.parseInt(b.readLine());

System.out.println("NUMERO DONDE EMPIEZA");

int a=Integer.parseInt(V1.readLine());

System.out.println("NUMERO DONDE TERMINE");

int c=Integer.parseInt(V2.readLine());

int i=9;

int j=0;

int r=0;

if (a>c)

{

for (i=a; i>=c; i--)

{

r=n*i;

System.out.println(n+"*"+i+"="+r );

}

}

else

{

for (i=a; i<=c; i++)

{

r=n*i;

System.out.println(n+"*"+i+"="+r );

}

}

} catch (Exception e)

{

e.printStackTrace();

}

}

}

Page 12: Ejemplos de Programacion en Java William Loor

GENERAR LAS TABLAS DE MULTIPLICAR CON WHILE public static void main(String[] args) {

InputStreamReader isr= new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

try {

System.out.println("Ingrese El N° de la Tabla a Generar ");

String n=br.readLine();

System.out.println("Ingrese Valor Para A");

String a=br.readLine();

System.out.println("Ingrese Valor Para B");

String b=br.readLine();

int d= Integer.parseInt(n);

int u= Integer.parseInt(a);

int l= Integer.parseInt(b);

int k=0;

int p=0;

if(u<l){

int i=u;

while (i<=l) {

k=d*i;

System.out.println(d+"*"+i+"="+k);

i++;

}

}

else

{

int i=u;

while (i>=l) {

k=d*i;

System.out.println(d+"*"+i+"="+k);

i--;

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

Page 13: Ejemplos de Programacion en Java William Loor

VALIDAR TARJETAS DE CREDITOS

public class VALIDARTARJETACREDITOformaSencilla {

public static void main(String[] arg) {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

try {

System.out.println("Ingrese el número de targeta de crédito: ");

String nt = br.readLine();

int lg = nt.length();

int t;

if (lg == 16) {

int si = 0, sp = 0;

for (int i = 0; i < lg ; i++) {

int d = Integer.parseInt("" + nt.charAt(i));

if ((i + 1) % 2 == 0) {

sp = sp + d;

} else {

d = d * 2;

if (d > 9) {

d = d - 9; }

si = si + d;

} }

t = si + sp;

int k = Integer.parseInt("" + nt.charAt(0));

if ((t % 10)==0 && (t<=150)) {

if (k==3) {

System.out.println("America Express");

} else {

if (k==4){

System.out.println("Visa");

} else{

if (k==5) {

System.out.println("Mastercard");

} else{

if (k==6){

System.out.println("Discover");

} else{

System.out.println("Tarjeta inválida");

} } } }

Page 14: Ejemplos de Programacion en Java William Loor

System.out.println("Tarjeta válida");

} else{

System.out.println("Tarjeta inválida");

}

} else {

System.out.println("Tarjeta inválida");

} } catch (Exception e) {

} } }

CONCATENACION(llamar Clases)

public class IngresaNumerosYSacaLetras {

public static void main(String[] args) {

InputStreamReader sr = new InputStreamReader(System.in);

BufferedReader b = new BufferedReader(sr);

try{

System.out.println("Ingrese un Numero entre el 1 y el 999");

String txt = b.readLine();

int L = txt.length();

String Cad = "";

if (L==1) {

Clase1 c1 = new Clase1();

Cad = c1.concatenar(txt,Cad);

}

if (L==2) {

Clase2 c2 = new Clase2();

Cad = c2.concatenar(txt, Cad);

}

if (L==3) {

Clase3 c3 = new Clase3();

Cad = c3.concatenar(txt,Cad);

}

System.out.println("El Resultado es:"+Cad);

} catch(Exception e) {

e.printStackTrace();

}

}

}

Page 15: Ejemplos de Programacion en Java William Loor

public class Clase1 {

public String concatenar(String text, String cad) {

int a = text.length();

String c = "" + text.charAt(a - 1);

int t=Integer.parseInt(c);

if (a==2) {

if(t!=0)

cad+=" y ";

}

if (a==3) {

String c1 = "" + text.charAt(1);

int t1=Integer.parseInt(c1);

if(t1!=0 && t!=0)

cad+=" y ";

}

if(text.equalsIgnoreCase("0"))

cad+="Cero";

else if (c.equalsIgnoreCase("1"))

cad += "uno";

else if (c.equalsIgnoreCase("2"))

cad += "dos";

else if (c.equalsIgnoreCase("3"))

cad += "tres";

else if (c.equalsIgnoreCase("4"))

cad += "cuatro";

else if (c.equalsIgnoreCase("5"))

cad += "cinco";

else if (c.equalsIgnoreCase("6"))

cad += "seis";

else if (c.equalsIgnoreCase("7"))

cad += "siete";

else if (c.equalsIgnoreCase("8"))

cad += "ocho";

else if (c.equalsIgnoreCase("9"))

cad += "nueve";

return cad;

}

}

public class Clase2 {

public String concatenar(String txt, String cad) {

int a = Integer.parseInt(txt);

Page 16: Ejemplos de Programacion en Java William Loor

int a1 = txt.length();

if (a1 == 3) {

String g = "" + txt.charAt(1);

String g1 = "" + txt.charAt(2);

g = g + g1;

a = Integer.parseInt(g);

}

if (a>=10 && a<=15) {

if(a == 10)

cad += "diez";

if(a == 11)

cad += "once";

if(a == 12)

cad += "doce";

if(a == 13)

cad += "trece";

if(a == 14)

cad += "catorce";

if(a == 15)

cad += "quince";

return cad;

} else {

int b = txt.length();

String v = "" + txt.charAt(b - 2);

if (v.equalsIgnoreCase("1"))

cad += "Diez ";

if (v.equalsIgnoreCase("2"))

cad += "Veinte ";

if (v.equalsIgnoreCase("3"))

cad += "Treinta ";

if (v.equalsIgnoreCase("4"))

cad += "Cuarenta ";

if (v.equalsIgnoreCase("5"))

cad += "Cincuenta ";

if (v.equalsIgnoreCase("6"))

cad += "Sesenta ";

if (v.equalsIgnoreCase("7"))

cad += "Setenta ";

if (v.equalsIgnoreCase("8"))

cad += "Ochenta ";

if (v.equalsIgnoreCase("9"))

cad += "Noventa ";

Page 17: Ejemplos de Programacion en Java William Loor

Clase1 sm = new Clase1();

String cad1 = sm.concatenar(txt, cad);

return cad1;

}

}

}

public class Clase3 {

public String concatenar(String txt, String cad)

{

int a = txt.length();

String c = "" + txt.charAt(a - 3);

String g = ""+txt.charAt(1);

String g1 = ""+txt.charAt(2);

if(txt.equalsIgnoreCase("100")&& g.equalsIgnoreCase("0")&& g1.equalsIgnoreCase("0"))

cad+="Cien";

else if(c.equalsIgnoreCase("1"))

cad += "ciento ";

else if (c.equalsIgnoreCase("2"))

cad += "doscientos ";

else if (c.equalsIgnoreCase("3"))

cad += "trecientos ";

else if (c.equalsIgnoreCase("4"))

cad += "cuatrocientos ";

else if (c.equalsIgnoreCase("5"))

cad += "quinientos ";

else if (c.equalsIgnoreCase("6"))

cad += "seiscientos ";

else if (c.equalsIgnoreCase("7"))

cad += "setecientos ";

else if (c.equalsIgnoreCase("8"))

cad += "ochocientos ";

else if (c.equalsIgnoreCase("9"))

cad += "novecientos ";

Clase2 sm = new Clase2();

String cad2 = sm.concatenar(txt, cad);

return cad2;

}

}

Page 18: Ejemplos de Programacion en Java William Loor

JAVA DESKTOP APPLICATION EJEMPLO “HOLA MUNDO”

public class HolaMundo {

public static void main( String args[] ) {

System.out.println( "Hola Mundo!" ) ;

}

}

private void

jButton1MouseClicked(java.awt.event.MouseEvent

evt) {

this.jTextField1.setText("HOLA MUNDO CRUEL");

CONCATENAR CLASES public class IngresarDatos {

Ejemplo13062011View fr ;

public IngresarDatos(Ejemplo13062011View fr) {

this.fr = fr;

}

int b =0;

int suma(){

int b = fr.a + 100;

return b;

}

}

public class Ejemplo13062011View

int a = 0 ;

public Ejemplo13062011View

private void jButton1MouseClicked

a = Integer.parseInt(jTextField1.getText()) ;

a = a + 25;

this.jTextField2.setText(""+a);

private void jButton2MouseClicked

IngresarDatos sm = new IngresarDatos(this); this.jTextField3.setText(""+sm.suma());

Page 19: Ejemplos de Programacion en Java William Loor

EL MAYOR DE TRES VALORES

private void jButton1MouseClicked(java.awt.event.MouseEvent

evt) {

int a = Integer.parseInt(jTextField1.getText());

int b = Integer.parseInt(jTextField2.getText());

int c = Integer.parseInt(jTextField3.getText());

if (a>b&&a>c) {

this.jTextField4.setText(""+a);

} else {

if (b>a&&b>c) {

this.jTextField4.setText(""+b);

} else {

this.jTextField4.setText(""+c);

}

}

VALIDAR TARJETA DE CRÉDITO private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

String nt =jTextField1.getText();

int lg = nt.length();

int t;

if (lg == 16) {

int si = 0, sp = 0;

for (int i = 0; i < lg ; i++) {

int d = Integer.parseInt("" +

nt.charAt(i));

if ((i + 1) % 2 == 0) {

sp = sp + d;

} else {

d = d * 2;

Page 20: Ejemplos de Programacion en Java William Loor

if (d > 9) {

d = d - 9;

}

si = si + d;

}

}

t = si + sp;

int k = Integer.parseInt("" + nt.charAt(0));

if ((t % 10)==0 && (t<=150)) {

if (k==3){

this.jTextField2.setText("America Express");

}

else{

if (k==4){

this.jTextField2.setText("Visa");

}

else{

if (k==5){

this.jTextField2.setText("Mastercard");

}

else{

if (k==6){

this.jTextField2.setText("Discover");

}

else{

this.jTextField3.setText("Tarjeta inválida");

}

}

}

}

Page 21: Ejemplos de Programacion en Java William Loor

this.jTextField3.setText("Tarjeta válida");

}

else{

this.jTextField3.setText("Tarjeta inválida");

}

}

else {

this.jTextField3.setText("Tarjeta inválida");

}

VALIDAR CÉDULA private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

String nc=(jTextField1.getText());

int t;

int lg=nc.length();

if (lg == 10) {

int si = 0, sp = 0;

for (int i = 0; i < lg - 1; i++) {

int d = Integer.parseInt("" + nc.charAt(i));

if ((i + 1) % 2 == 0) {

sp = sp + d;

} else {

d = d * 2;

if (d > 9) {

d = d - 9;

}

si = si + d;

}

}

t = si + sp;

t = t % 10;

int k = Integer.parseInt("" + nc.charAt(lg - 1));

Page 22: Ejemplos de Programacion en Java William Loor

t=t+k;

if ((t % 10)==0) {

this.jTextField2.setText("Cédula correcta");

} else {

this.jTextField2.setText("Cédula incorrecta");

}

}

else {

this.jTextField2.setText("Cédula incorrecta");

}

MAYOR DE TRES NÚMEROS (listbox) private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

DefaultListModel modelo = new DefaultListModel();

try

{

int N1 = Integer.parseInt(this.jTextField1.getText());

int N2 =Integer.parseInt(this.jTextField2.getText());

int N3 =Integer.parseInt(this.jTextField3.getText());

if (N1> N2 & N1>N3)

{

modelo.addElement(N1);

jList1.setModel(modelo);

}

else

{

if (N2> N1 && N2>N3)

{

modelo.addElement(N2);

jList1.setModel(modelo);

} else

{

modelo.addElement(N3);

jList1.setModel(modelo);

}

Page 23: Ejemplos de Programacion en Java William Loor

}

}

catch (Exception e)

{

e.printStackTrace ();

}

INGRESA UNA CADENA (la muestra Invertida)

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

try{

String txt = this.jTextField1.getText();

int a= txt.length();

String Cad="";

for(int i= a-1;i>=0;i--)

{

Cad+=txt.charAt(i);

}

this.jTextField2.setText(Cad);

}

catch (Exception e)

{

e.printStackTrace();

}

COMO MOSTRAR DATOS EN UN LISTBOX

import javax.swing.DefaultListModel;

DefaultListModel Modelo = new DefaultListModel();

Modelo.addElement("UNO");

Modelo.addElement("DOS");

Modelo.addElement("TRES");

Modelo.addElement("CUATRO");

this.jList1.setModel(Modelo);

Page 24: Ejemplos de Programacion en Java William Loor

SERIE DE NÚMEROS ( de-A – Hasta-B en Listbox) import javax.swing.DefaultListModel;

DefaultListModel modelo = new DefaultListModel();

try {

int A = Integer.parseInt(this.jTextField1.getText());

int B = Integer.parseInt(this.jTextField2.getText());

int i=A;

int r=0;

if (A>B)

{

for (i=A; i>=B; i--)

{

r=i;

String dl = (""+i );

modelo.addElement(i);

this.jList1.setModel(modelo);

}

}

else

{

for (i=A; i<=B; i++)

{

r=i;

String dl = (""+i );

modelo.addElement(i);

this.jList1.setModel(modelo);

}

}

} catch (Exception e)

{

e.printStackTrace();

}

Page 25: Ejemplos de Programacion en Java William Loor

TABLA DE MULTIPLICAR N(desde –Hasta) import javax.swing.DefaultListModel;

DefaultListModel modelo = new DefaultListModel();

try{

int n = Integer.parseInt(this.jTextField1.getText());

int a = Integer.parseInt(this.jTextField2.getText());

int c = Integer.parseInt(this.jTextField3.getText());

int i=9;

int r = 0;

if (a>c)

{

for (i=a; i>=c; i--)

{

r=n*i;

String dl = (n+"*"+i+"="+r );

modelo.addElement(dl);

this.jList1.setModel(modelo);

}

}

else

{

for (i=a; i<=c; i++)

{

r=n*i;

String dl = (n+"*"+i+"="+r );

modelo.addElement(dl);

}

this.jList1.setModel(modelo);

}

}

catch (Exception e)

{

e.printStackTrace();

}

Page 26: Ejemplos de Programacion en Java William Loor

GENERAR TABLAS DE MULTIPLICAR SENCILLA private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

DefaultListModel modelo = new DefaultListModel();

Try {

int t = Integer.parseInt(this.jTextField1.getText());

int r = 0;

for (int ii=0 ; ii<=12; ii++)

{

R = t* ii;

String dl = (t+ "*" +ii+ "=" +r);

modelo.addElement(dl);

jList1.setModel(modelo);

}

} catch (Exception e) {

e.printStackTrace();

}

LLENAR DATOS EN DATA TABLE(tabla de datos) private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

Object [][] d1=new Object [2][5];

for (int i=0; i<=1;i++)

{

for(int j=0;j<=4;j++)

{

d1[i][j]=1;

}

}

String [] cl=new String [5];

for (int g=0;g<=4;g++)

{

cl[g]="dato"+(g+1);

}

DefaultTableModel dtm=new

DefaultTableModel(d1,cl);

this.jTable1.setModel(dtm);

}

Page 27: Ejemplos de Programacion en Java William Loor

LLENAR DATOS2 private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

int a= Integer.parseInt(this.jTextField1.getText());

int b= Integer.parseInt(this.jTextField2.getText());

Object [][] d1 = new Object [a][b];

String [] cl = new String [b];

for (int i=0; i<=a-1;i++)

{

for(int j=0;j<=b-1;j++)

{

if (i==j)

{

d1[i][j]=1;

} else {

d1 [i][j] = 0;

}

cl[j] = "numeros" + (j+1);

}

}

DefaultTableModel dtm=new DefaultTableModel(d1,cl);

this.jTable1.setModel(dtm);

}

Mostral si El Numero es Par, Impar, Nulo, PROMEDIOS. private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

String sd = jTextField1.getText();

int s = sd.length();

double a = 0;

double b = 0;

double c = 0;

double d = 0;

double f = 0;

double g = 0;

double k = 0;

for (int i = 0; i < s; i++) {

int v = Integer.parseInt("" + sd.charAt(i));

if (v==0) {

Page 28: Ejemplos de Programacion en Java William Loor

a+=1;

this.jTextField4.setText(""+a);

} else {

if (v%2==0) {

b+=1;

c=c+v;

d=c/b;

this.jTextField2.setText(""+b);

this.jTextField5.setText(""+d);

}

else{

f+=1;

g=g+v;

k=g/f;

this.jTextField3.setText(""+f);

this.jTextField6.setText(""+k);

}

}

}

Mostrar si El Numero es Par, Impar, Nulo, Positivo y

Negativo (en un LISTBOX)

import javax.swing.DefaultListModel;

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

DefaultListModel modelo = new DefaultListModel();

try{

String sd = jTextField1.getText();

int valor = Integer.parseInt(sd);

if (valor ==0) {

modelo.addElement(valor);

this.jList3.setModel(modelo);

}

Page 29: Ejemplos de Programacion en Java William Loor

if(valor % 2 == 0 && valor > 0){

modelo.addElement(valor);

this.jList1.setModel(modelo);

this.jList4.setModel(modelo);

}

else if(valor % 2 == 0 && valor < 0)

{

modelo.addElement(valor);

this.jList1.setModel(modelo);

this.jList5.setModel(modelo);

}

else if(valor % 2 != 0 && valor > 0) {

modelo.addElement(valor);

this.jList2.setModel(modelo);

this.jList4.setModel(modelo);

}

else if(valor % 2 != 0 && valor< 0){

modelo.addElement(valor);

this.jList2.setModel(modelo);

this.jList5.setModel(modelo);

}

}

catch (Exception e)

{

e.printStackTrace();

}

Page 30: Ejemplos de Programacion en Java William Loor

Mostral si El Numero es Par, Impar, Nulo, Positivo y

Negativo (en un DATA TABLE)

import javax.swing.table.DefaultTableModel;

public class VerificarsiElNumeroesPosNegParImpEnDataTableView extends FrameView {

int fpos=0, fneg=0,fpar=0,fimp=0,fnul=0;

Object [][] datos = new Object[8][5];

String [] columnas = {"Positivos","Negativos","Pares","Impares","Nulos"};

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

int num = Integer.parseInt(jTextField1.getText());

if (num==0) {

datos[fnul][4]= num;

fnul+=1;

}

if (num % 2 == 0 && num > 0){

datos[fpar][2]= num;

fpar +=1;

datos[fpos][0]= num;

fpos+=1;

}

else if(num % 2 == 0 && num < 0){

datos[fpar][2]= num;

fpar +=1;

datos[fneg][1]= num;

fneg+=1;

}

else if(num % 2 != 0 && num > 0){

datos[fimp][3]= num;

fimp +=1;

datos[fpos][0]= num;

fpos+=1;

}

else if(num % 2 != 0 && num < 0){

datos[fimp][3]= num;

fimp +=1;

datos[fneg][1]= num;

fneg+=1;

}

DefaultTableModel dtm = new DefaultTableModel(datos, columnas);

this.jTable1.setModel(dtm);

Page 31: Ejemplos de Programacion en Java William Loor

RECUPERACION DE LA PRUEBA

import javax.swing.DefaultListModel;

DefaultListModel modelo = new DefaultListModel();

try{

String sd = jTextField1.getText();

int valor = Integer.parseInt(sd);

if (valor ==0) {

modelo.addElement(valor);

this.jList3.setModel(modelo);

}

if(valor % 2 == 0 && valor > 0){

modelo.addElement(valor);

this.jList1.setModel(modelo);

this.jList4.setModel(modelo);

} else if(valor % 2 == 0 && valor < 0)

{

modelo.addElement(valor);

this.jList1.setModel(modelo);

this.jList5.setModel(modelo);

}

else if(valor % 2 != 0 && valor > 0) {

modelo.addElement(valor);

this.jList2.setModel(modelo);

this.jList4.setModel(modelo);

}

else if(valor % 2 != 0 && valor< 0){

modelo.addElement(valor);

this.jList2.setModel(modelo);

this.jList5.setModel(modelo);

}

}

catch (Exception e)

{

e.printStackTrace();

}

Page 32: Ejemplos de Programacion en Java William Loor

FACTURA

import javax.swing.table.DefaultTableModel;

public class FactView extends FrameView {

double t=0;

double k=0;

double l=0;

double acu=0;

int fila=0;

int fila1=0;

Object [][] tabla;int fila =0;

Object [][] fact;

String []

col={"Nº","Detalle","Cantidad","Precio","Total"};

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

int h= Integer.parseInt(this.jTextField1.getText());

tabla=new Object[h][5];

this.jTextField1.setEnabled(false);

this.jButton1.setEnabled(false);

this.jTextField2.setEnabled(true);

this.jTextField3.setEnabled(true);

this.jTextField4.setEnabled(true);

this.jButton2.setEnabled(true);

DefaultTableModel modelo=new DefaultTableModel(tabla,vector) ;

this.jTable1.setModel(modelo);

} this.fact = new Object [Integer.parseInt(this.jTextField1.getText())] [5];

this.jButton2.setEnabled(true);

this.jButton1.setEnabled(false);

}

private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {

double b= Double.valueOf(this.jTextField3.getText());

double p= Double.valueOf(this.jTextField4.getText());

int h= Integer.parseInt(this.jTextField1.getText());

tabla[fila][0]=fila+1;

Page 33: Ejemplos de Programacion en Java William Loor

tabla[fila1][1]=this.jTextField2.getText();

tabla[fila1][2]=this.jTextField3.getText();

tabla[fila1][3]= this.jTextField4.getText();

tabla[fila1][4]=p*b;

fila1+=1;

this.jTextField2.setText("");

this.jTextField3.setText("");

this.jTextField4.setText("");

if (fila1==h) {

this.jTextField1.setEnabled(true);

this.jButton1.setEnabled(true);

this.jTextField2.setEnabled(false);

this.jTextField3.setEnabled(false);

this.jTextField4.setEnabled(false);

this.jButton2.setEnabled(false);

}

t=b*p;

this.jTextField5.setText(""+t);

k=(t*12)/100;

this.jTextField6.setText(""+k);

l=k+t;

acu=acu+l;

this.jTextField5.setText(""+acu);

DefaultTableModel modelo=new DefaultTableModel(tabla,vector) ;

this.jTable1.setModel(modelo);

Page 34: Ejemplos de Programacion en Java William Loor

APLICACIONES MÓBILES Sumar dos Números

int a = Integer.parseInt(""+this.primcan.getString()) ;

int b = Integer.parseInt(""+this.segcan.getString()) ;

int r=a+b;

this.resultado.setString("" + r);

Mayor de Tres Números

Page 35: Ejemplos de Programacion en Java William Loor

int a= Integer.parseInt(textField4.getString());

int b= Integer.parseInt(textField5.getString());

int c= Integer.parseInt(textField6.getString());

if (a>b && a>c){

this.textField7.setString("El número mayor es: "+a);

}

else if (b>a && b>c){

this.textField7.setString("El número mayor es: "+b);

}

else{

this.textField7.setString("El número mayor es: "+c);

}

Caracter Invertido

String txt= (this.inv.getString());

int a= txt.length();

String Cad="";

for(int i= a-1;i>=0;i--)

{

Cad+=txt.charAt(i);

}

this.result.setString(""+Cad);

Page 36: Ejemplos de Programacion en Java William Loor

Validar Cédula

String nc = (this.textField.getString());

int t;

int lg = nc.length();

if (lg == 10) {

int si = 0, sp = 0;

for (int i = 0; i < lg - 1; i++) {

int d = Integer.parseInt("" + nc.charAt(i));

if ((i + 1) % 2 == 0) {

sp = sp + d;

} else {

d = d * 2;

if (d > 9) {

d = d - 9;

}

si = si + d;

}

}

t = si + sp;

t = t % 10;

int k = Integer.parseInt("" + nc.charAt(lg - 1));

Page 37: Ejemplos de Programacion en Java William Loor

t = t + k;

if ((t % 10) == 0) {

this.textField1.setString("Cédula correcta");

} else {

this.textField1.setString("Cédula incorrecta");

}

} else {

this.textField1.setString("Cédula incorrecta");

}

Validar Tarjeta

String nt =textField.getString();

int lg = nt.length();

int t;

if (lg == 16) {

int si = 0, sp = 0;

for (int i = 0; i < lg ; i++) {

int d = Integer.parseInt("" + nt.charAt(i));

if ((i + 1) % 2 == 0) {

sp = sp + d;

} else {

d = d * 2;

if (d > 9) {

d = d - 9;

}

Page 38: Ejemplos de Programacion en Java William Loor

si = si + d;

}

}

t = si + sp;

int k = Integer.parseInt("" + nt.charAt(0));

if ((t % 10)==0 && (t<=150)) {

if (k==3){

this.textField1.setString("America Express");

} else{

if (k==4){

this.textField1.setString("Visa");

}

else {

if (k==5){

this.textField1.setString("Mastercard");

} else {

if (k==6){

this.textField1.setString("Discover");

} Else {

this.textField1.setString("Tarjeta inválida");

} } } }

this.textField2.setString("Tarjeta válida");

}

else{

this.textField2.setString("Tarjeta inválida");

}

}

else {

this.textField2.setString("Tarjeta inválida");

}

Page 39: Ejemplos de Programacion en Java William Loor

Concatenamiento

try{

String txt = this.textField.getString();

int L = txt.length();

String Cad = "";

if (L==1)

{

clase1 c1 = new clase1();

Cad = c1.concatenar(txt,Cad);

}

if (L==2)

{

clase2 c2 = new clase2();

Cad = c2.concatenar(txt, Cad);

}

if (L==3)

{

clase3 c3 = new clase3();

Cad = c3.concatenar(txt,Cad);

}

this.textField1.setString(""+Cad);

} catch(Exception e) {

e.printStackTrace(); }

Page 40: Ejemplos de Programacion en Java William Loor

public class clase1 {

public String concatenar(String text,

String cad)

{

int a = text.length();

String c = "" + text.charAt(a - 1);

int t=Integer.parseInt(c);

if (a==2)

{

if(t!=0)

cad+=" y ";

}

if (a==3)

{

String c1 = "" + text.charAt(1);

int t1=Integer.parseInt(c1);

if(t1!=0 && t!=0)

cad+=" y ";

}

if(text.equals("0"))

cad+="Cero";

else if (c.equals("1"))

cad += "uno";

else if (c.equals("2"))

cad += "dos";

else if (c.equals("3"))

cad += "tres";

else if (c.equals("4"))

cad += "cuatro";

else if (c.equals("5"))

cad += "cinco";

else if (c.equals("6"))

cad += "seis";

else if (c.equals("7"))

cad += "siete";

else if (c.equals("8"))

cad += "ocho";

else if (c.equals("9"))

cad += "nueve";

return cad;

}

}

public class clase2 {

public String concatenar(String

txt, String cad)

{

int a = Integer.parseInt(txt);

int a1 = txt.length();

if (a1 == 3)

{

String g = "" + txt.charAt(1);

String g1 = "" + txt.charAt(2);

g = g + g1;

a = Integer.parseInt(g);

}

if (a>=10 && a<=15)

{

if(a == 10)

cad += "diez";

if(a == 11)

cad += "once";

if(a == 12)

cad += "doce";

if(a == 13)

cad += "trece";

if(a == 14)

cad += "catorce";

if(a == 15)

cad += "quince";

return cad;

}

else

{

int b = txt.length();

String v = "" + txt.charAt(b - 2);

if (v.equals("1"))

cad += "Diez ";

if (v.equals("2"))

cad += "Veinte ";

if (v.equals("3"))

cad += "Treinta ";

if (v.equals("4"))

cad += "Cuarenta ";

if (v.equals("5"))

cad += "Cincuenta ";

if (v.equals("6"))

cad += "Sesenta ";

if (v.equals("7"))

cad += "Setenta ";

if (v.equals("8"))

cad += "Ochenta ";

if (v.equals("9"))

cad += "Noventa ";

clase1 sm = new clase1();

String cad1 = sm.concatenar(txt,

cad);

return cad1;

}

}

}

Page 41: Ejemplos de Programacion en Java William Loor

public class clase3 {

String concatenar(String txt, String cad) {

int b=txt.length();

int k = Integer.parseInt(""+txt.charAt(1));

int k1 = Integer.parseInt(""+txt.charAt(2));

String a=""+txt.charAt(b-3);

int aa=Integer.parseInt(a);

if (txt.equals("100")&& (k==0)&&(k1==0))

cad="cien";

else if (aa== 1) {

cad = "ciento ";

}

else if (aa == 2) {

cad = "docientos ";

} else if (aa== 3) {

cad = "trecientos ";

} else if (aa== 4) {

cad = "cuatrocientos ";

} else if (aa == 5) {

cad = "quinientos ";

} else if (aa == 6) {

cad = "seiscientos ";

} else if (aa == 7) {

cad = "setecientos ";

} else if (aa == 8) {

cad = "ochocientos ";

} else if (aa == 9) {

cad = "novecientos ";

}

clase2 cl2 = new clase2();

cad =cl2.concatenar(txt, cad);

return cad;

}

}

Page 42: Ejemplos de Programacion en Java William Loor

Menú Formulario(O. Matemáticas)

double a = Double.parseDouble(textField.getString());

double b = Double.parseDouble(textField1.getString());

double su=a+b;

this.textField2.setString(""+su);

double a = Double.parseDouble(textField3.getString());

double b= Double.parseDouble(textField4.getString());

double re=a-b;

this.textField5.setString(""+re);

double a = Double.parseDouble(textField6.getString());

double b= Double.parseDouble(textField7.getString());

double re=a*b;

this.textField8.setString(""+re);

double a = Double.parseDouble(textField9.getString());

double b= Double.parseDouble(textField10.getString());

double re=a/b;

this.textField11.setString(""+re);

Page 43: Ejemplos de Programacion en Java William Loor

Menú Choice Group Operaciones Matemáticas

double a= Double.parseDouble(this.txt1.getString()) ;

double b= Double.parseDouble(this.txt2.getString()) ;

double r = 0;

if (this.choiceGroup.getSelectedIndex()==0) {

r = a+ b;

this.txt3.setString(""+r);}

else if (this.choiceGroup.getSelectedIndex()==1){

r = a-b;

this.txt3.setString(""+r); }

else if(this.choiceGroup.getSelectedIndex()==1) {

r = a - b;

this.txt3.setString(""+r);}

else if(this.choiceGroup.getSelectedIndex()==2){

r = a * b;

this.txt3.setString(""+r); }

else if(this.choiceGroup.getSelectedIndex()==3)

if (a == 0 && b != 0) {

this.txt3.setString("ERROR");

} else {

r = a / b;

this.txt3.setString(""+r); }

Page 44: Ejemplos de Programacion en Java William Loor

Convertidor de Grados Centigrados

(en un Menú Choice Group)

if (choiceGroup.getSelectedIndex()==0) {

double f= Double.parseDouble(this.textField.getString());

f= (f*9/5)+32;

this.textField1.setString(""+f);

}

else if (choiceGroup.getSelectedIndex()==1) {

double f= Double.parseDouble(this.textField.getString());

f= (f-32)*5/9;

this.textField1.setString(""+f);

}

else if (choiceGroup.getSelectedIndex()==2) {

double f= Double.parseDouble(this.textField.getString());

f = f - 273.15;

this.textField1.setString(""+f);

}

else if (choiceGroup.getSelectedIndex()==3) {

double c= Double.parseDouble(this.textField.getString());

c = c - 273.15;

this.textField1.setString(""+c1);

}

Page 45: Ejemplos de Programacion en Java William Loor

Convertidor de Grados Centigrados

(en un Menú Formulario)

// write pre-action user code here

double Fa,Ce,Ke;

int C= this.textField.getString().length();

int F= this.textField1.getString().length();

int K= this.textField2.getString().length();

if (C>0 && F==0 && K==0){

double c= Double.parseDouble(textField.getString());

Fa=((((c*9)/5))+32);

Ke=(c+273.15);

this.textField1.setString(""+Fa);

this.textField2.setString(""+Ke);

}

else if (F>0 && C==0 && K==0){

double f= Double.parseDouble(textField1.getString());

Ce=(f-32)/1.8;

Ke=(f+459.67)/1.8;

this.textField.setString(""+Ce);

this.textField2.setString(""+Ke);

}

else if (K>0 && C==0 && F==0){

double k= Double.parseDouble(textField2.getString());

Ce=(k-273.5);

Fa= ((9*k)/5)-459.67;

this.textField.setString(""+Ce);

this.textField1.setString(""+Fa);

}

Boton Limpiar

// write pre-action user code here

this.textField.setString("");

this.textField1.setString("");

this.textField2.setString("");

Page 46: Ejemplos de Programacion en Java William Loor

FACTORES DE CONVERSIÓN(Menú Formularios)

double M1,K1,Me1;

int M= this.textField.getString().length();

int K= this.textField1.getString().length();

int Me= this.textField2.getString().length();

if (M>0 && K==0 && Me==0){

double m= Double.parseDouble(textField.getString());

K1 = (m*1.6093);

Me1 =(m*1609.3404);

this.textField1.setString(""+K1);

this.textField2.setString(""+Me1);

}

if (K>0 && M==0 && Me==0){

double k=

Double.parseDouble(textField1.getString());

M1 = (k*0.6212);

Me1 =(k*1000);

this.textField.setString(""+M1);

this.textField2.setString(""+Me1);

}

if (Me>0 && K==0 && M==0){

double me= Double.parseDouble(textField2.getString());

K1 = (me/1000);

M1 =(me/0.6212)/1000;

this.textField1.setString(""+K1);

this.textField.setString(""+M1);

}

Boton Limpiar

// write pre-action user code here

this.textField.setString("");

this.textField1.setString("");

this.textField2.setString("");

Page 47: Ejemplos de Programacion en Java William Loor

double M1,K1,Me1;

int M= this.textField.getString().length();

int K= this.textField1.getString().length();

int Me= this.textField2.getString().length();

if (M>0 && K==0 && Me==0){

double m= Double.parseDouble(textField.getString());

K1 = (m*1.6093);

Me1 =(m*1609.3404);

this.textField1.setString(""+K1);

this.textField2.setString(""+Me1);

}

if (K>0 && M==0 && Me==0){

double k= Double.parseDouble(textField1.getString());

M1 = (k*0.6212);

Me1 =(k*1000);

this.textField.setString(""+M1);

this.textField2.setString(""+Me1);

}

if (Me>0 && K==0 && M==0){

double me= Double.parseDouble(textField2.getString());

K1 = (me/1000);

M1 =(me/0.6212)/1000;

this.textField1.setString(""+K1);

this.textField.setString(""+M1);

}

Boton Limpiar

// write pre-action user code here

this.textField3.setString("");

this.textField4.setString("");

this.textField5.setString("");

Page 48: Ejemplos de Programacion en Java William Loor

LIST

GENERAR SERIE DE A hasta B en un List

// write post-action user code here

int A = Integer.parseInt(this.textField.getString());

int B = Integer.parseInt(this.textField1.getString());

if (A>B)

{

int c = 0;

for (int i=A; i>=B; i--)

{

this.list.insert(c,""+i,null);

c++;

}

} else {

int c = 0;

for (int i=A; i<=B; i++)

{

this.list.insert(c, ""+i , null);

c++;

}

}

En el Back del List

// write pre-action user code

this.list.deleteAll();

list = new List("list", Choice.IMPLICIT);

list.append("", null);

list.addCommand(getBackCommand());

list.setCommandListener(this);

list.setSelectedFlags(new boolean[] { false });

Limpiar

// write pre-action user code here

this.textField.setString("");

this.textField1.setString("");

Page 49: Ejemplos de Programacion en Java William Loor

GENERAR TABLA DE A hasta B( En Un List)

// write pre-action user code here

switchDisplayable(null, getList());

int n = Integer.parseInt(this.textField.getString());

int a = Integer.parseInt(this.textField1.getString());

int c = Integer.parseInt(this.textField2.getString());

int i=9;

int r = 0;

if (a>c)

{ for (i=a; i>=c; i--) {

r=n*i;

int c1 = 0;

String dl = (n+"*"+i+"="+r );

this.list.insert(c1,""+dl,null);

}

} else {

int c1 = 0;

for (i=a; i<=c; i++) {

r=n*i;

String dl = (n+"*"+i+"="+r );

this.list.insert(c1,""+dl,null);

}

}

Limpiar

// write pre-action user code here

this.textField.setString("");

this.textField1.setString("");

this.textField2.setString("");

En el Back del List

// write pre-action user code here

this.list.deleteAll();

list = new List("", Choice.IMPLICIT);

list.append("", null);

list.addCommand(getBackCommand());

list.setCommandListener(this);

list.setSelectedFlags(new boolean[] { false });

switchDisplayable(null, getForm());

Page 50: Ejemplos de Programacion en Java William Loor

UNION DE TABLA Y SERIE de A hasta B

// write post-action user code here

int a= Integer.parseInt(this.textField.getString());

int b= Integer.parseInt(this.textField1.getString());

if(a<b){

int c=0;

for (int i = a; i <= b; i++) {

this.Serie.insert(c,""+i , null);

c++;

}

}

else{

int c=0;

for (int i =

a; i >= b; i--) {

this.Serie.insert(c,""+i , null);

c++;

}

}

Limpiar

// write pre-action user code here

this.textField.setString("");

this.textField1.setString("");

List Serie

// write post-action user code here

this.Menu.deleteAll();

Serie = new List("list1", Choice.IMPLICIT);

Serie.append("", null);

Serie.addCommand(getBackCommand3());

Serie.setCommandListener(this);

Serie.setSelectedFlags(new boolean[] { false });

OK Menú List

// write pre-action user code here

if(this.Menu.getSelectedIndex()==0)

switchDisplayable(null, getForm());

if(this.Menu.getSelectedIndex()==1)

switchDisplayable(null, getForm1());

Page 51: Ejemplos de Programacion en Java William Loor

// write post-action user code here

int n=Integer.parseInt(textField2.getString());

int a=Integer.parseInt(textField3.getString());

int b=Integer.parseInt(textField4.getString());

if (a<b)

{

int c=0;

for (int i = a; i < b+1; i++) {

int t=n*i;

this.Tabla.insert(c,""+n+"*"+i+"="+t,null);

c++;

}

}

else{

int c=0;

for (int i = a; i > b-1; i--) {

int t=n*i;

this.Tabla.insert(c,""+n+"*"+i+"="+t,null);

c++;

}

}

}

private Image img,img1;

// write post-action user code here

try {

img = img.createImage("/4.png");

img1 = img1.createImage("/8.png");

} catch (Exception e) {

System.err.println(e.getMessage()); }

this.Menu.insert(0, "Serie de A hasta B", img);

this.Menu.insert(1,"Tabla de Multiplicar", img1);

// write pre-action user code here

this.textField2.setString("");

this.textField3.setString("");

this.textField4.setString("");

Back list Tabla

// write post-action user code here

this.Menu.deleteAll();

Tabla = new List("list2", Choice.IMPLICIT);

Tabla.append("", null);

Tabla.addCommand(getBackCommand4());

Tabla.setCommandListener(this);

Tabla.setSelectedFlags(new boolean[] { false });

Page 52: Ejemplos de Programacion en Java William Loor

UNIÓN TEMPERATURA Y FACTORES DE CONVERSÍON

//

write pre-action user code here

double M1,K1,Me1;

int M= this.textField.getString().length();

int K= this.textField1.getString().length();

int Me= this.textField2.getString().length();

if (M>0 && K==0 && Me==0){

double m=

Double.parseDouble(textField.getString());

K1 = (m*1.6093);

Me1 =(m*1609.3404);

this.textField1.setString(""+K1);

this.textField2.setString(""+Me1); }

if (K>0 && M==0 && Me==0) {

double k= Double.parseDouble(textField1.getString());

M1 = (k*0.6212);

Me1 =(k*1000);

this.textField.setString(""+M1);

this.textField2.setString(""+Me1); }

if (Me>0 && K==0 && M==0) {

double me=

Double.parseDouble(textField2.getString());

K1 = (me/1000);

M1 =(me/0.6212)/1000;

this.textField1.setString(""+K1);

this.textField.setString(""+M1); }

OK Menú List

// write pre-action user code here

if(this.FactoresdeConversión.getSelectedIndex()==0)

switchDisplayable(null, getSplashScreen());

if(this.FactoresdeConversión.getSelectedIndex()==1)

switchDisplayable(null, getSplashScreen1());

if(this.FactoresdeConversión.getSelectedIndex()==2)

switchDisplayable(null, getSplashScreen2());

Limpiar

// write pre-action user code here

this.textField.setString("");

this.textField1.setString("");

this.textField2.setString("");

Page 53: Ejemplos de Programacion en Java William Loor

// write pre-action user code here

double Kil1,Lib1,Gra1;

int Kil= this.textField3.getString().length();

int Lib= this.textField4.getString().length();

int Gra= this.textField5.getString().length();

if (Kil>0 && Lib==0 && Gra==0)

{

double ki= Double.parseDouble(textField3.getString());

Lib1 = (ki*2.2046);

Gra1 =(ki*1000);

this.textField4.setString(""+Lib1);

this.textField5.setString(""+Gra1);

}

if (Lib>0 && Kil==0 && Gra==0){

double li= Double.parseDouble(textField4.getString());

Kil1 = (li*0.453592);

Gra1 =( Lib /513.4); // Error

this.textField3.setString(""+Kil1);

this.textField5.setString(""+Gra1);

}

if (Gra>0 && Kil==0 && Lib==0){

double gr= Double.parseDouble(textField5.getString());

Kil1 = (gr/1000);

Lib1 =(gr/1000)*2.20;

this.textField3.setString(""+Kil1);

this.textField4.setString(""+Lib1);

}

Limpiar

// write pre-action user code here

this.textField3.setString("");

this.textField4.setString("");

this.textField5.setString("");

Page 54: Ejemplos de Programacion en Java William Loor

// write pre-action user code here

double Fa,Ce,Ke;

int C= this.textField6.getString().length();

int F= this.textField7.getString().length();

int K= this.textField8.getString().length();

if (C>0 && F==0 && K==0)

{

double c= Double.parseDouble(textField6.getString());

Fa=((((c*9)/5))+32);

Ke=(c+273.15);

this.textField7.setString(""+Fa);

this.textField8.setString(""+Ke);

}

else if (F>0 && C==0 && K==0)

{

double f= Double.parseDouble(textField7.getString());

Ce=(f-32)/1.8;

Ke=(f+459.67)/1.8;

this.textField6.setString(""+Ce);

this.textField8.setString(""+Ke);

}

else if (K>0 && C==0 && F==0)

{

double k= Double.parseDouble(textField8.getString());

Ce=(k-273.5);

Fa= ((9*k)/5)-459.67;

this.textField6.setString(""+Ce);

this.textField7.setString(""+Fa);

}

Limpiar

// write pre-action user code here

this.textField6.setString("");

this.textField7.setString("");

this.textField8.setString("");

private Image img,img1,img2;

// write post-action user code here

try {

img = img.createImage("/4.png");

img1 = img1.createImage("/5.png");

img2 = img2.createImage("/6.png");

} catch (Exception e) {

System.err.println(e.getMessage());

}

this.FactoresdeConversión.insert(0, "Longitud", img);

this.FactoresdeConversión.insert(1,"Peso", img1);

this.FactoresdeConversión.insert(2,"Temperatura", img2);

Page 55: Ejemplos de Programacion en Java William Loor

CLASE CANVAS

public class HelloMIDlet extends MIDlet implements CommandListener {

MIDPCanvas canvas;

MIDPCanvas_1 canvas1;

MIDPCanvas_2 canvas2;

public HelloMIDlet() {

canvas = new MIDPCanvas(this);

canvas1 = new MIDPCanvas_1(this);

canvas2 = new MIDPCanvas_2(this);

public class MIDPCanvas extends Canvas implements CommandListener {

HelloMIDlet demo;

public MIDPCanvas(HelloMIDlet p) {

try {

// Set up this canvas to listen to command events

setCommandListener(this);

// Add the Exit command

addCommand(new Command("Exit", Command.EXIT, 1));

demo = p;

} catch (Exception e) {

e.printStackTrace();

}

}

public void paint(Graphics g) {

g.setColor(255,0,0);

g.fillRect(0, 0,this.getWidth(), this.getHeight());

g.setColor(0,0,0);

g.drawString("SISTEMAS", 0, 0, Graphics.TOP | Graphics.LEFT); }

public void commandAction(Command command, Displayable displayable) {

if (command.getCommandType()==command.EXIT)

Display.getDisplay(demo).setCurrent(demo.getList());

OK

// write pre-action user code here

if (this.list.getSelectedIndex()==0)

Display.getDisplay(this).setCurrent(canvas);

if (this.list.getSelectedIndex()==1)

Display.getDisplay(this).setCurrent(canvas1);

if (this.list.getSelectedIndex()==2)

Display.getDisplay(this).setCurrent(canvas2);

// write post-action user code here

this.list.insert(0, "Rojo",null );

this.list.insert(1, "Verde", null);

this.list.insert(2, "Azul", null);

Page 56: Ejemplos de Programacion en Java William Loor

public class MIDPCanvas_1 extends Canvas implements CommandListener {

HelloMIDlet demo1;

public MIDPCanvas_1(HelloMIDlet a) {

try {

// Set up this canvas to listen to command events

setCommandListener(this);

// Add the Exit command

addCommand(new Command("Exit", Command.EXIT, 1));

demo1 = a;

} catch (Exception e) {

e.printStackTrace(); } }

public void paint(Graphics g) {

g.setColor(0,255,0);

g.fillRect(0, 0,this.getWidth(), this.getHeight());

g.setColor(0,0,0);

g.drawString("SISTEMAS", 0, 0, Graphics.TOP | Graphics.LEFT);

public void commandAction(Command command, Displayable displayable) {

if (command.getCommandType()==command.EXIT)

Display.getDisplay(demo1).setCurrent(demo1.getList());

public class MIDPCanvas_2 extends Canvas implements CommandListener {

HelloMIDlet demo2;

public MIDPCanvas_2(HelloMIDlet o) {

try {

// Set up this canvas to listen to command events

setCommandListener(this);

// Add the Exit command

addCommand(new Command("Exit", Command.EXIT, 1));

demo2 = o;

} catch (Exception e) {

e.printStackTrace(); } }

public void paint(Graphics g) {

g.setColor(0,0,255);

g.fillRect(0, 0,this.getWidth(), this.getHeight());

g.setColor(0,0,0);

g.drawString("SISTEMAS", 0, 0, Graphics.TOP | Graphics.LEFT);

}

public void commandAction(Command command, Displayable displayable) {

if (command.getCommandType()==command.EXIT)

Display.getDisplay(demo2).setCurrent(demo2.getList());

} }

Page 57: Ejemplos de Programacion en Java William Loor

CREAR ARCO Y RECTANGULO( con clase Canvas)

public class HelloMIDlet extends MIDlet implements

CommandListener {

int R,G,B;

GRAFICO gra;

GRAFICO2 gra2;

int a1,a2, a3, a4, a5;

public HelloMIDlet() {

gra= new GRAFICO (this);

gra2 = new GRAFICO2 (this);

}

Ok list

// write pre-action user code here

if (this.list.getSelectedIndex()==0)

switchDisplayable(null, getForm1());

if (this.list.getSelectedIndex()==1)

switchDisplayable(null, getForm2());

ok Form1

// write pre-action user code here

int a=Integer.parseInt(this.textField.getString()) ;

int b=Integer.parseInt(this.textField3.getString()) ;

R = Integer.parseInt(this.textField5.getString()) ;

G = Integer.parseInt(this.textField6.getString()) ;

B = Integer.parseInt(this.textField7.getString()) ;

Display.getDisplay(this).setCurrent(gra);

a1=a;

a2=b;

ok form2

// write pre-action user code here

int c=Integer.parseInt(this.textField1.getString()) ;

int d=Integer.parseInt(this.textField2.getString()) ;

int e=Integer.parseInt(this.textField4.getString()) ;

R = Integer.parseInt(this.textField8.getString()) ;

G = Integer.parseInt(this.textField9.getString()) ;

B = Integer.parseInt(this.textField10.getString()) ;

a3=c;

a4=d;

a5=e;

Page 58: Ejemplos de Programacion en Java William Loor

public class GRAFICO extends Canvas implements CommandListener {

HelloMIDlet MIDl;

String texto = "";

public GRAFICO(HelloMIDlet M) {

try {

addCommand(new Command("Back", Command.EXIT, 1));

this.MIDl = M;

} catch (Exception e) {

public void paint(Graphics g) {

g.setColor(MIDl.R, MIDl.G, MIDl.B);

g.fillRect(0, 0, getWidth(), getHeight());

g.setColor(255,255,0);

g.drawString(texto, 0, 0, Graphics.TOP | Graphics.LEFT);

g.drawRect(10,20 , MIDl.a2, MIDl.a1);

g.setColor(0,255,0);

g.fillRect(10, 20, MIDl.a2, MIDl.a1);

g.drawString("5to A de Sistemas", 0, 0, Graphics.TOP | Graphics.LEFT);

public void commandAction(Command command, Displayable displayable) {

if(command.getCommandType()==Command.EXIT)

Display.getDisplay(MIDl).setCurrent(MIDl.getForm2());

public class GRAFICO2 extends Canvas implements CommandListener {

HelloMIDlet MIDlet1;

public GRAFICO2(HelloMIDlet p) {

try {

this.MIDlet1 = p;

} catch (Exception e) {

public void paint(Graphics g) {

g.setColor(MIDlet1.R, MIDlet1.G, MIDlet1.B);

g.fillRect(0, 0, getWidth(), getHeight());

g.setColor(255,255,0);

g.drawArc(MIDlet1.a5, MIDlet1.a5, MIDlet1.a5, MIDlet1.a5, MIDlet1.a3, MIDlet1.a4);

g.setColor(0,255,0);

g.fillArc(MIDlet1.a5, MIDlet1.a5, MIDlet1.a5, MIDlet1.a5, MIDlet1.a3, MIDlet1.a4);

g.drawString("Ricardo Rivadeneira ", 0, 0, Graphics.TOP | Graphics.LEFT); }

public void commandAction(Command command, Displayable displayable) {

if(command.getCommandType()==Command.EXIT)

Display.getDisplay(MIDlet1).setCurrent(MIDlet1.getForm1());

Page 59: Ejemplos de Programacion en Java William Loor

BARRA ESTADÍSTICA (en Canvas)

public graficos(HelloMIDlet M) {

try {

// setCommandListener(this);

//addCommand(new Command("Exit",

Command.EXIT, 1));

this.midlet = M;

public void paint(Graphics g) {

g.setColor(159,89,0);

g.fillRect(0, 0, 300, 300);

g.setColor(150, 8, 182);

g.drawString("5to A de Sistemas"+" "+Txt,0, 0,

Graphics.TOP | Graphics.LEFT);

g.fillRect(10, 150+ (100-

(midlet.pr1*2)),50,(midlet.pr1*2));

g.setColor(200, 50, 200);

g.fillRect(60, 150+ (100-

(midlet.pr2*2)),50,(midlet.pr2*2));

g.setColor(210,240, 240);

g.fillRect(110, 150+ (100-

(midlet.pr3*2)),50,(midlet.pr3*2));

g.setColor(35, 255, 249);

g.fillRect(160, 150+ (100-

(midlet.Pr4*2)),50,(midlet.Pr4*2));

g.setColor(55, 255, 255);

g.drawLine(10,250,220,250);

g.drawLine(10,20,10,250); }

// write pre-action user code here

int v1=Integer.parseInt(textField.getString());

int v2=Integer.parseInt(textField1.getString());

int v3=Integer.parseInt(textField2.getString());

int v4=Integer.parseInt(textField3.getString());

int s=v1+v2+v3+v4;

pr1=v1*100/s;

pr2=v2*100/s;

pr3=v3*100/s;

Pr4=v4*100/s;

Display.getDisplay(this).setCurrent(gra);

public class HelloMIDlet graficos gra;

int pr1,pr2,pr3,Pr4;

public HelloMIDlet() {

gra=new graficos(this);

protected void keyPressed(int keyCode) {

if(keyCode==getKeyCode(UP)) {

Txt = "Arriba";

repaint(); }

if(keyCode==getKeyCode(DOWN)) {

Txt = "Abajo";

repaint(); }

if(keyCode==getKeyCode(RIGHT)) {

Txt = "Derecha";

repaint(); }

if(keyCode==getKeyCode(LEFT)) {

Txt = "Izquierda";

repaint(); }

if(keyCode==getKeyCode(FIRE)) {

Txt = "Centro";

repaint(); } }

public void commandAction(Command command, Displayable displayable) {

if (command.getCommandType()==command.EXIT)

Display.getDisplay(midlet).setCurrent(midlet.getForm());

Page 60: Ejemplos de Programacion en Java William Loor

PRIMER JUEGO SENCILLO(Caballito de Mar)

import javax.microedition.lcdui.game.*;

import java.io.*;

import java.util.Random;

public class canvas1 extends GameCanvas implements Runnable {

String texto = "Ricardo Rivadeneira";

HelloMIDlet midletAnterior;

private boolean isPlay; // Game Loop runs when isPlay is true

private long delay; // To give thread consistency

private int X, X1,x2,x3, Y, Y1,y2,y3,cont; // To hold current position of the 'X'

private int width; // To hold screen width

private int height; // To hold screen height

private Sprite sp;

private Image image,ima,imag1,imag2,fondo;

private TiledLayer tiledMapa;

private LayerManager LM;

* constructor

public canvas1(HelloMIDlet midletAnterior) {

super(true);

width = getWidth();

height = getHeight();

try {

image= Image.createImage("/image.png");

} catch (IOException e) {

throw new RuntimeException ("Unable to load Image fish: "+e);

}

sp = new Sprite (image,image.getWidth()/3,image.getHeight());

X = width /2 - image.getWidth()/2;

OK Form

// write pre-action user code here

can.start();

Display.getDisplay(this).setCurrent(can);

Page 61: Ejemplos de Programacion en Java William Loor

Y = height - image.getHeight()-20;

delay = 100;

try {

ima= Image.createImage("/disparo.png");

//fondo= Image.createImage("/fondo.png");

} catch (IOException e) {

throw new RuntimeException ("Unable to load Image fish: "+e);

}

Y1= 0;

X1=0 ;

try {

imag1= Image.createImage("/disparo.png");

imag2= Image.createImage("/disparo.png");

} catch (IOException e) {

throw new RuntimeException ("Unable to load Image fish: "+e); }

y2=0;

x2=width;

y3=0;

x3=width/2;

try {

tiledMapa = initMapa();

} catch (Exception e) {

throw new RuntimeException ("Unable to init tiledmapa: "+e); }

LM = new LayerManager();

LM.append(tiledMapa); }

public void start() {

isPlay = true;

Thread t = new Thread(this);

t.start(); }

//controlar los movimientos del Caballito

private void input() {

int keyStates = getKeyStates();

if ((keyStates & LEFT_PRESSED) != 0) {

X = Math.max(0, X - 10);

sp.setTransform(Sprite.TRANS_MIRROR);

}

if ((keyStates & RIGHT_PRESSED) !=0 ) {

Page 62: Ejemplos de Programacion en Java William Loor

X = Math.min(width-20, X + 10);

sp.setTransform(Sprite.TRANS_NONE);

}

if ((keyStates & UP_PRESSED) !=0 ) {

Y = Math.max(0, Y - 10);

sp.setTransform(Sprite.TRANS_NONE);

}

if ((keyStates & DOWN_PRESSED) !=0 ) {

if (Y+10< height)

Y = Math.min(height-60, Y + 10);

sp.setTransform(Sprite.TRANS_NONE);

} }

private TiledLayer initMapa() throws Exception {

Image tiledImage;

tiledImage = Image.createImage("/mapa.png");

TiledLayer tiledLayer = new TiledLayer(16,16,tiledImage,16,16);

int[] mapa = {

24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,

24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,

21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,

5, 17, 5, 5, 21, 5, 5, 22, 12, 13, 5, 5, 22, 5, 5, 5,

5, 5, 5, 5, 21, 5, 5, 22, 5, 12, 5, 5, 22, 5, 5, 5,

11, 3, 5, 5, 5, 21, 6, 9, 15, 5, 22, 5, 5, 6, 9, 10,

11, 3, 5, 5, 5, 21, 5, 11, 5, 5, 22, 5, 5, 5, 9, 10,

18, 18, 18, 18, 8, 18, 15, 18, 18, 18, 18, 18, 18, 18, 18, 18,

17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,

14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,

11, 3, 11, 11, 5, 21, 5, 5, 5, 5, 22, 5, 5, 5, 9, 10,

11, 3, 5, 5, 5, 21, 5, 5, 5, 5, 22, 5, 5, 5, 9, 10,

5, 5, 9, 5, 21, 5, 5, 22, 5, 6, 5, 5, 22, 5, 5, 5,

5, 22, 5, 5, 21, 9, 5, 22, 9, 19, 10, 5, 22, 5, 5, 5,

7, 5, 5, 5, 23, 4, 5, 5, 18, 6, 5, 13, 5, 5, 5, 5,

5, 24, 5, 5, 24, 9, 17, 5, 8, 9, 5, 5, 17, 5, 5, 5, } ;

for (int i=0; i < mapa.length; i++) {

int columna = i % 16;

int fila = (i - columna) / 16;

tiledLayer.setCell(columna,fila,mapa[i]); }

return tiledLayer; }

public void run() {

Random md = new Random();

Page 63: Ejemplos de Programacion en Java William Loor

System.out.println("Ricardo");

while (isPlay == true) {

input();

sp.nextFrame();

sp.setPosition(X, Y);

Y1 = Y1 + 10;

y2 =y2+10;

y3=y3+10;

if(Y1 > height || y2 > height || y3 > height){

Y1 = 0;

X1 =(int)(md.nextDouble()*width);

y2 = 0;

x2 =(int)(md.nextDouble()*width);

y3 = 0;

x3 = (int)(md.nextDouble()*width); }

if(sp.collidesWith(ima,X1,Y1,true)) {

cont++;

sp.setTransform(Sprite.TRANS_MIRROR_ROT90);

if (cont==3) {

isPlay = false;

} else {

isPlay = true;

sp.setTransform(Sprite.TRANS_MIRROR_ROT270);

} repaint(); }

if(sp.collidesWith(imag1,x2,y2,true)) {

sp.setTransform(Sprite.TRANS_MIRROR_ROT90);

if (cont==3) {

isPlay = false;

} else {

isPlay = true;

sp.setTransform(Sprite.TRANS_MIRROR_ROT270);

} repaint(); }

if(sp.collidesWith(imag2,x3,y3,true)) {

cont++;

sp.setTransform(Sprite.TRANS_MIRROR_ROT90);

if (cont==3) {

isPlay = false;

} else {

isPlay = true;

sp.setTransform(Sprite.TRANS_MIRROR_ROT270);

Page 64: Ejemplos de Programacion en Java William Loor

} repaint(); }

//para q evitar q la thread de saltos, prueba al ejecutar el programa sin el delay

try { Thread.sleep(delay); }

catch (InterruptedException ie) { }

} }

public void paint(Graphics g) {

g.setColor(255,255,255); //Asigna Color

//Dibujar un rectángulo relleno en toda la pantalla

g.fillRect(0, 0, getWidth(), getHeight());

LM.paint(g,0,0); //carga la imagen de fondo

// g.drawImage(fondo,0,0,Graphics.TOP | Graphics.LEFT);

g.drawString("Ricardo", 0, 0, Graphics.TOP | Graphics.LEFT);

g.drawImage(ima,x3,y3,Graphics.TOP | Graphics.LEFT); //disparo1

g.drawImage(imag1,X1,Y1,Graphics.TOP | Graphics.LEFT); //disparo2

g.drawImage(imag2,x2,y2,Graphics.TOP | Graphics.RIGHT); //disparo3

g.setColor(0,255,0);

sp.paint(g); }

protected void keyPressed(int keyCode) {

if(keyCode == getKeyCode(UP)) {

this.isPlay=true;

this.run();

texto = "Arriba";

repaint();

} else if(keyCode == getKeyCode(DOWN)) {

texto = "Abajo";

repaint();

} else if(keyCode == getKeyCode(RIGHT)) {

X = Math.min(width, X + 10);

sp.setTransform(Sprite.TRANS_NONE);

texto = "Derecha";

repaint();

} else if(keyCode == getKeyCode(LEFT)) {

X = Math.max(0, X - 10);

sp.setTransform(Sprite.TRANS_MIRROR);

texto = "Izquierda";

repaint(); } }

public void commandAction(Command command, Displayable displayable) {

if(command.getCommandType() == Command.EXIT)

Page 65: Ejemplos de Programacion en Java William Loor

Display.getDisplay(midletAnterior).setCurrent(midletAnterior.getForm());

}

}

CALCULADORA

public class Calculadora {

public static void main(String[] args) {

Calcul obj = new Calcul();

obj.setVisible(true);

obj.setLocationRelativeTo(null);

}

}

public class libreria {

private String cadena;

private double resultado;

private boolean suma;

private boolean resta;

private boolean multiplicacion;

private boolean division;

public libreria()

{

cadena ="";

resta=false;

suma=false;

division=false;

multiplicacion=false;

}

public String concatenamiento(String cadena)

{

this.cadena = this.cadena + cadena;

return this.cadena;

Page 66: Ejemplos de Programacion en Java William Loor

}

public void suma(String cadena)

{

this.resultado = Double.parseDouble(cadena);

suma = true;

this.cadena = "";

}

public void resta(String cadena)

{

this.resultado = Double.parseDouble(cadena);

resta = true;

this.cadena = "";

}

public void division(String cadena)

{

this.resultado = Double.parseDouble(cadena);

division = true;

this.cadena = "";

}

public void multiplicacion(String cadena)

{

this.resultado = Double.parseDouble(cadena);

multiplicacion = true;

this.cadena = "";

}

public double resultado (String numero)

{

if(suma == true)

{

resultado = resultado + Double.parseDouble(numero);

}

else if(resta == true)

{

resultado = resultado - Double.parseDouble(numero);

}

else if(division == true)

{

resultado = resultado / Double.parseDouble(numero);

Page 67: Ejemplos de Programacion en Java William Loor

}

else if(multiplicacion == true)

{

resultado = resultado * Double.parseDouble(numero);

}

suma=false; resta=false; multiplicacion=false; division=false;

return this.resultado;

}

}

public class Calcul extends javax.swing.JFrame {

/** Creates new form Calcul */

libreria obj = new libreria();

public Calcul() {

initComponents();

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jButton17 = new javax.swing.JButton();

jTextField1 = new javax.swing.JTextField();

jButton1 = new javax.swing.JButton();

jButton2 = new javax.swing.JButton();

jButton3 = new javax.swing.JButton();

jButton4 = new javax.swing.JButton();

jButton5 = new javax.swing.JButton();

Page 68: Ejemplos de Programacion en Java William Loor

jButton6 = new javax.swing.JButton();

jButton7 = new javax.swing.JButton();

jButton8 = new javax.swing.JButton();

jButton9 = new javax.swing.JButton();

jButton10 = new javax.swing.JButton();

jButton11 = new javax.swing.JButton();

jButton12 = new javax.swing.JButton();

jButton13 = new javax.swing.JButton();

jButton14 = new javax.swing.JButton();

jButton15 = new javax.swing.JButton();

jButton16 = new javax.swing.JButton();

jButton18 = new javax.swing.JButton();

jButton19 = new javax.swing.JButton();

jButton20 = new javax.swing.JButton();

jLabel1 = new javax.swing.JLabel();

jButton17.setText("jButton17");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("CALCULADORA");

jTextField1.setEditable(false);

jTextField1.setHorizontalAlignment(javax.swing.JTextField.LEFT);

jTextField1.setText("0");

jButton1.setText("9");

jButton1.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton1MouseClicked(evt);

}

});

jButton2.setText("8");

jButton2.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton2MouseClicked(evt);

}

});

Page 69: Ejemplos de Programacion en Java William Loor

jButton3.setText("7");

jButton3.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton3MouseClicked(evt);

}

});

jButton4.setText("4");

jButton4.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton4MouseClicked(evt);

}

});

jButton5.setText("5");

jButton5.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton5MouseClicked(evt);

}

});

jButton6.setText("6");

jButton6.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton6MouseClicked(evt);

}

});

jButton7.setText("1");

jButton7.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton7MouseClicked(evt);

}

});

jButton8.setText("2");

jButton8.addMouseListener(new java.awt.event.MouseAdapter() {

Page 70: Ejemplos de Programacion en Java William Loor

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton8MouseClicked(evt);

}

});

jButton9.setText("3");

jButton9.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton9MouseClicked(evt);

}

});

jButton10.setText("0");

jButton10.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton10MouseClicked(evt);

}

});

jButton11.setText("=");

jButton11.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton11MouseClicked(evt);

}

});

jButton12.setText("+");

jButton12.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton12MouseClicked(evt);

}

});

jButton13.setText("/");

jButton13.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton13MouseClicked(evt);

}

Page 71: Ejemplos de Programacion en Java William Loor

});

jButton14.setText("*");

jButton14.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton14MouseClicked(evt);

}

});

jButton15.setText("-");

jButton15.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton15MouseClicked(evt);

}

});

jButton16.setText(".");

jButton16.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton16MouseClicked(evt);

}

});

jButton18.setText("ON");

jButton18.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton18MouseClicked(evt);

}

});

jButton18.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton18ActionPerformed(evt);

}

});

jButton19.setText("OFF");

jButton19.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

Page 72: Ejemplos de Programacion en Java William Loor

jButton19MouseClicked(evt);

}

});

jButton19.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton19ActionPerformed(evt);

}

});

jButton20.setText("AC");

jButton20.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

jButton20MouseClicked(evt);

}

});

jLabel1.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N

jLabel1.setText("CASIO 360");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

.addGroup(layout.createSequentialGroup()

.addComponent(jButton4)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jButton5)

.addGap(13, 13, 13)

.addComponent(jButton6))

.addGroup(layout.createSequentialGroup()

.addComponent(jButton7)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

Page 73: Ejemplos de Programacion en Java William Loor

.addComponent(jButton8)

.addGap(13, 13, 13)

.addComponent(jButton9))

.addGroup(layout.createSequentialGroup()

.addComponent(jButton10)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jButton16, javax.swing.GroupLayout.PREFERRED_SIZE, 25,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jButton11))

.addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING,

javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)

.addGroup(layout.createSequentialGroup()

.addComponent(jButton3)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jButton2)

.addGap(13, 13, 13)

.addComponent(jButton1)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 53,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jButton19, javax.swing.GroupLayout.PREFERRED_SIZE, 57,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,

false)

.addComponent(jButton12, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addComponent(jButton15, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

Page 74: Ejemplos de Programacion en Java William Loor

.addComponent(jButton14, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addComponent(jButton13))

.addGap(18, 18, 18)

.addComponent(jButton20)))

.addGap(23, 23, 23))

.addGroup(layout.createSequentialGroup()

.addGap(113, 113, 113)

.addComponent(jLabel1)

.addContainerGap(76, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addComponent(jLabel1)

.addGap(29, 29, 29)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jButton18)

.addComponent(jButton19))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jButton3)

.addComponent(jButton1)

.addComponent(jButton2)

.addComponent(jButton13))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jButton4)

.addComponent(jButton6)

Page 75: Ejemplos de Programacion en Java William Loor

.addComponent(jButton5)

.addComponent(jButton14))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jButton7)

.addComponent(jButton9)

.addComponent(jButton15)

.addComponent(jButton8))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jButton12)

.addComponent(jButton11)

.addComponent(jButton16)

.addComponent(jButton10)))

.addGroup(layout.createSequentialGroup()

.addGap(7, 7, 7)

.addComponent(jButton20, javax.swing.GroupLayout.PREFERRED_SIZE, 93,

javax.swing.GroupLayout.PREFERRED_SIZE)))

.addGap(57, 57, 57))

);

pack();

}// </editor-fold>

private void jButton7MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("1"));

}

private void jButton10MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("0"));

}

Page 76: Ejemplos de Programacion en Java William Loor

private void jButton8MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("2"));

}

private void jButton9MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("3"));

}

private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("4"));

}

private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("5"));

}

private void jButton6MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("6"));

}

private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("7"));

}

private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("8"));

}

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

Page 77: Ejemplos de Programacion en Java William Loor

jTextField1.setText(obj.concatenamiento("9"));

}

private void jButton16MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText(obj.concatenamiento("."));

}

private void jButton12MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

obj.suma(jTextField1.getText());

}

private void jButton11MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

jTextField1.setText("" + obj.resultado(this.jTextField1.getText()));

}

private void jButton15MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

obj.resta(jTextField1.getText());

}

private void jButton14MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

obj.multiplicacion(jTextField1.getText());

}

private void jButton13MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

obj.division(jTextField1.getText());

}

private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

}

Page 78: Ejemplos de Programacion en Java William Loor

private void jButton19MouseClicked(java.awt.event.MouseEvent evt) {

this.jButton1.setEnabled(false);

this.jButton2.setEnabled(false);

this.jButton3.setEnabled(false);

this.jButton4.setEnabled(false);

this.jButton5.setEnabled(false);

this.jButton6.setEnabled(false);

this.jButton7.setEnabled(false);

this.jButton8.setEnabled(false);

this.jButton9.setEnabled(false);

// TODO add your handling code here:

}

private void jButton18MouseClicked(java.awt.event.MouseEvent evt) {

this.jButton1.setEnabled(true);

this.jButton2.setEnabled(true);

this.jButton3.setEnabled(true);

this.jButton4.setEnabled(true);

this.jButton5.setEnabled(true);

this.jButton6.setEnabled(true);

this.jButton7.setEnabled(true);

this.jButton8.setEnabled(true);

this.jButton9.setEnabled(true);

// TODO add your handling code here:

}

private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

}

private void jButton20MouseClicked(java.awt.event.MouseEvent evt) {

this.jTextField1.setText(null);

libreria obj = new libreria();

//public Calcul() {

initComponents();

Page 79: Ejemplos de Programacion en Java William Loor

// TODO add your handling code here:

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new Calcul().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton10;

private javax.swing.JButton jButton11;

private javax.swing.JButton jButton12;

private javax.swing.JButton jButton13;

private javax.swing.JButton jButton14;

private javax.swing.JButton jButton15;

private javax.swing.JButton jButton16;

private javax.swing.JButton jButton17;

private javax.swing.JButton jButton18;

private javax.swing.JButton jButton19;

private javax.swing.JButton jButton2;

private javax.swing.JButton jButton20;

private javax.swing.JButton jButton3;

private javax.swing.JButton jButton4;

private javax.swing.JButton jButton5;

private javax.swing.JButton jButton6;

private javax.swing.JButton jButton7;

private javax.swing.JButton jButton8;

private javax.swing.JButton jButton9;

private javax.swing.JLabel jLabel1;

private javax.swing.JTextField jTextField1;

Page 80: Ejemplos de Programacion en Java William Loor

// End of variables declaration

DIFERENCIA DE TRES

FORMULARIO

private void button1MouseClicked(java.awt.event.MouseEvent evt) {

cJuego R = new cJuego();

R.Iniciar();

R.Jugar();

R.Visualizar(list1);

public enum eLADO {

CARA , SELLO ;

}

public class cDato {

public Double FrecAbsol ;

public Double FrecRelat ;

Page 81: Ejemplos de Programacion en Java William Loor

public String Dato;

public Integer repeticiones;

public cDato Sig ;

}

public class cMonteCarlos {

private cDato PriDato;

private Integer Total;

public void ingresar(String vDato, int vRep) {

cDato nuevo;

nuevo = new cDato();

nuevo.Dato = vDato;

nuevo.repeticiones = vRep;

cDato aux;

if (PriDato == null) {

PriDato = nuevo;

} else {

aux = PriDato;

while (aux.Sig != null) {

}

aux = aux.Sig;

aux.Sig = nuevo;

Total += vRep;

aux = PriDato;

double acumula = 0;

while (aux != null) {

aux.FrecRelat = Double.valueOf(aux.repeticiones / Total);

aux.FrecAbsol = aux.FrecRelat + acumula;

acumula = aux.FrecAbsol;

Page 82: Ejemplos de Programacion en Java William Loor

aux = aux.Sig;

}

}

}

public String generar() {

Random rnd = new Random();

Double na;

na = rnd.nextDouble();

cDato aux;

aux = PriDato;

while (aux != null && na > aux.FrecAbsol) {

}

aux = aux.Sig;

return aux.Dato;

}

}

public class cJugada {

public eLADO LADO ;

public cJugada sig ;

}

public class cJuego {

private cJugada Pri;

private double Premio;

private int NoLanz;

private int NC;

private int NS;

private double Utilidad;

private int dif;

public void Iniciar() {

Pri = null;

Page 83: Ejemplos de Programacion en Java William Loor

Premio = 1.2;

NoLanz = 10;

NC = 0;

NS = 0;

Utilidad = 0;

}

public void Jugar() {

Random rnd = new Random();

int dif = 0;

cJugada nuevo;

while (dif < 3 && NoLanz > 0) {

nuevo = new cJugada();

if (rnd.nextDouble() < 0.5) {

nuevo.LADO = eLADO.CARA;

} else {

nuevo.LADO = eLADO.SELLO;

}

nuevo.sig = Pri;

Pri = nuevo;

if (nuevo.LADO == eLADO.CARA) {

NC++;

} else {

NS++;

}

dif = Math.abs(NC - NS);

NoLanz--;

}

}

public void Visualizar(java.awt.List vLB) {

vLB.removeAll();

cJugada aux = Pri;

Page 84: Ejemplos de Programacion en Java William Loor

while (aux != null) {

vLB.add(aux.LADO.toString());

aux = aux.sig;

}

if (dif == 3) {

vLB.add("Premio =" + String.valueOf(Premio));

}

}

}

COLA DE ESPERA SIMPLE

FORMULARIO

Nº de Horas = textbox

Resultado = listbox

Satir = button

Ejecutar = button = cCola oCola;

oCola = new cCola();

oCola.Iniciar(Integer.valueOf(textField1.getText()));

oCola.Ejecutar();

oCola.Visualizar(list1);

CLASES

public class cDatoMC {

public Double FrecAbsol ;

public Double FrecRelat ;

public String Dato;

public Integer repeticiones;

public cDatoMC Sig ;

Page 85: Ejemplos de Programacion en Java William Loor

}

public class cMonteCarlos {

private cDatoMC PriDato;

private int Total;

public void ingresar(String vDato, int vRep) {

cDatoMC nuevo;

nuevo = new cDatoMC();

nuevo.Dato = vDato;

nuevo.repeticiones = vRep;

nuevo.Sig=null;

cDatoMC aux;

if (PriDato == null) {

PriDato = nuevo;

} else {

aux = PriDato;

while (aux.Sig != null) {

aux = aux.Sig;

}

aux.Sig = nuevo;

}

Total += vRep;

aux = PriDato;

double acumula = 0;

while (aux != null) {

aux.FrecRelat = (double) aux.repeticiones / (double) Total;

aux.FrecAbsol = (double) aux.FrecRelat + (double) acumula;

acumula = aux.FrecAbsol;

aux = aux.Sig;

}

Page 86: Ejemplos de Programacion en Java William Loor

}

public String generar() {

Random rnd = new Random();

Double na;

na = rnd.nextDouble();

cDatoMC aux;

aux = PriDato;

while (aux != null && na > aux.FrecAbsol) {

aux = aux.Sig;

}

return aux.Dato;

}

}

public class cNodo {

public int Tiemllegada;

public int TiemEspera;

public int Horallegada;

public int HoraSalida;

public int TiemLibre;

public cNodo sig;

}

public class cCola {

public int NoTAXLLegada;

public int NoTAXSalida;

public int TiemLibre;

public int TotalHoras;

Page 87: Ejemplos de Programacion en Java William Loor

cMonteCarlos MCarlosLlegada;

cMonteCarlos MCarlosSalida;

public cNodo PriNodo;

public void Iniciar(int vTHoras) {

NoTAXLLegada = 0;

NoTAXSalida = 0;

TiemLibre = 0;

TotalHoras = vTHoras * 60;

PriNodo = null;

MCarlosLlegada = new cMonteCarlos();

MCarlosSalida = new cMonteCarlos();

MCarlosLlegada.ingresar(String.valueOf(0), 2);

MCarlosLlegada.ingresar(String.valueOf(1), 2);

MCarlosLlegada.ingresar(String.valueOf(2), 1);

MCarlosLlegada.ingresar(String.valueOf(3), 2);

MCarlosLlegada.ingresar(String.valueOf(4), 1);

MCarlosLlegada.ingresar(String.valueOf(5), 2);

MCarlosLlegada.ingresar(String.valueOf(6), 1);

MCarlosLlegada.ingresar(String.valueOf(7), 4);

MCarlosLlegada.ingresar(String.valueOf(8), 2);

MCarlosLlegada.ingresar(String.valueOf(9), 2);

MCarlosLlegada.ingresar(String.valueOf(10), 1);

MCarlosLlegada.ingresar(String.valueOf(11), 1);

MCarlosLlegada.ingresar(String.valueOf(12), 2);

MCarlosLlegada.ingresar(String.valueOf(13), 2);

MCarlosSalida.ingresar(String.valueOf(2), 2);

MCarlosSalida.ingresar(String.valueOf(3), 4);

MCarlosSalida.ingresar(String.valueOf(4), 1);

MCarlosSalida.ingresar(String.valueOf(5), 2);

MCarlosSalida.ingresar(String.valueOf(6), 1);

MCarlosSalida.ingresar(String.valueOf(7), 2);

Page 88: Ejemplos de Programacion en Java William Loor

MCarlosSalida.ingresar(String.valueOf(8), 1);

MCarlosSalida.ingresar(String.valueOf(9), 4);

MCarlosSalida.ingresar(String.valueOf(10), 2);

MCarlosSalida.ingresar(String.valueOf(11), 1);

MCarlosSalida.ingresar(String.valueOf(12), 4);

}

public void Ejecutar() {

while (TotalHoras > 0) {

cNodo nuevo = new cNodo();

nuevo.Tiemllegada = Integer.valueOf(MCarlosLlegada.generar());

nuevo.TiemEspera = Integer.valueOf(MCarlosSalida.generar());

TotalHoras -= nuevo.Tiemllegada;

if (PriNodo == null) {

nuevo.Horallegada = nuevo.Tiemllegada;

nuevo.HoraSalida = nuevo.TiemEspera;

nuevo.TiemLibre = nuevo.Tiemllegada;

PriNodo = nuevo;

nuevo.sig = null;

} else {

cNodo aux = PriNodo;

while (aux.sig != null) {

aux = aux.sig;

}

nuevo.Horallegada = nuevo.Tiemllegada + aux.Horallegada;

if (aux.HoraSalida > nuevo.Horallegada) {

nuevo.HoraSalida = aux.HoraSalida + nuevo.TiemEspera;

nuevo.TiemLibre = 0;

} else {

Page 89: Ejemplos de Programacion en Java William Loor

nuevo.HoraSalida = nuevo.Horallegada + nuevo.TiemEspera;

nuevo.TiemLibre = nuevo.Horallegada - aux.HoraSalida;

}

aux.sig = nuevo;

nuevo.sig = null;

}

if (nuevo.Horallegada < TotalHoras) {

NoTAXLLegada++;

}

if (nuevo.HoraSalida < TotalHoras) {

NoTAXSalida++;

}

TiemLibre += nuevo.TiemLibre;

{

}

}

}

public void Visualizar(java.awt.List vlb) {

vlb.removeAll();

vlb.add(" Numero de Taxis que llegan = " +

String.valueOf(NoTAXLLegada));

vlb.add(" Numero de Taxis que Salen = " +

String.valueOf(NoTAXSalida));

vlb.add(" ------------------------------ ");

vlb.add(" N° H.Llegada H.Salida ");

cNodo aux = PriNodo;

int n = 1;

while (aux != null) {

vlb.add(String.valueOf(n) +" "+ String.valueOf(7 + (int)

(aux.Horallegada / 60))+ ":" + String.valueOf ((int)(aux.Horallegada %

Page 90: Ejemplos de Programacion en Java William Loor

60))+ " "+ String.valueOf(7 + (int) (aux.HoraSalida / 60)) + ":" +

String.valueOf((int)(aux.HoraSalida % 60)));

aux = aux.sig;

n++;

}

vlb.add(" Tiempo Libre de Parada " + String.valueOf((int) (TiemLibre /

60)) + ":" + String.valueOf(TiemLibre));

}

}

COLA DE ESPERA MULTIPLE private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

cColadeEspera oCola;

oCola = new cColadeEspera();

oCola.Iniciar(Integer.valueOf(TextField.getText()));

oCola.CalcularResultados();

oCola.Visualizar( List1, vlb); // TODO add your handling code here:

}

public class cDatoMC {

public Double FrecAbsol ;

public Double FrecRelat ;

public String Dato;

public Integer repeticiones;

public cDatoMC Sig ;

}

public class cMonteCarlos {

Page 91: Ejemplos de Programacion en Java William Loor

private cDatoMC PriDato;

private int Total;

public void ingresar(String vDato, int vRep) {

cDatoMC nuevo;

nuevo = new cDatoMC();

nuevo.Dato = vDato;

nuevo.repeticiones = vRep;

nuevo.Sig=null;

cDatoMC aux;

if (PriDato == null) {

PriDato = nuevo;

} else {

aux = PriDato;

while (aux.Sig != null) {

aux = aux.Sig;

}

aux.Sig = nuevo;

}

Total += vRep;

aux = PriDato;

double acumula = 0;

while (aux != null) {

aux.FrecRelat = (double) aux.repeticiones / (double) Total;

aux.FrecAbsol = (double) aux.FrecRelat + (double) acumula;

acumula = aux.FrecAbsol;

aux = aux.Sig;

}

Page 92: Ejemplos de Programacion en Java William Loor

}

public String generar() {

Random rnd = new Random();

Double na;

na = rnd.nextDouble();

cDatoMC aux;

aux = PriDato;

while (aux != null && na > aux.FrecAbsol) {

aux = aux.Sig;

}

return aux.Dato;

}

}

public class cCliente {

public int TEspera;

public int HLlegada;

public int HAtencion;

public Integer HEspera;

public Integer TiempAtencion;

public cCliente Sig;

public int TLlegada;

}

public class cColadeEspera {

private int TiempAtenBco;

cMonteCarlos MCLlegada;

cMonteCarlos MCTiempAtenc;

private int NoClieAtend;

private int NoClieCola;

Page 93: Ejemplos de Programacion en Java William Loor

private int MaxClieCola;

private cCliente NuevoClie;

private cCliente PriColaEsper;

private cCliente ClieCaja[];

private int SumTiempEsper;

private int Hora;

public void Iniciar(String vTAB) {

NoClieAtend = 0;

NoClieCola = 0;

MaxClieCola = 0;

SumTiempEsper = 0;

NuevoClie = null;

PriColaEsper = null;

ClieCaja = null;

ClieCaja[1] = new cCliente();

ClieCaja[2] = new cCliente();

TiempAtenBco = Hora * 60;

MCLlegada = new cMonteCarlos();

MCLlegada.ingresar(String.valueOf(0), 3);

MCLlegada.ingresar(String.valueOf(1), 8);

MCLlegada.ingresar(String.valueOf(2), 6);

MCLlegada.ingresar(String.valueOf(3), 3);

MCTiempAtenc = new cMonteCarlos();

MCTiempAtenc.ingresar(String.valueOf(1), 5);

MCTiempAtenc.ingresar(String.valueOf(2), 6);

MCTiempAtenc.ingresar(String.valueOf(3), 5);

MCTiempAtenc.ingresar(String.valueOf(4), 4);

Hora = 0;

}

Page 94: Ejemplos de Programacion en Java William Loor

private void IngresarCliente() {

if (NuevoClie == null) {

NuevoClie = new cCliente();

NuevoClie.TLlegada = Integer.valueOf(MCLlegada.generar());

NuevoClie.HLlegada = Hora;

}

if (NuevoClie.TLlegada == 0) {

if (PriColaEsper == null) {

PriColaEsper = NuevoClie;

} else {

cCliente aux;

aux = PriColaEsper;

while (aux.Sig != null) {

aux = aux.Sig;

}

aux.Sig = NuevoClie;

NuevoClie = new cCliente();

NuevoClie.TLlegada = Hora;

NuevoClie.TLlegada = Integer.valueOf(MCLlegada.generar());

}

}

}

private void AtenderCliente() {

for (int i = 0; i < 2; i++) {

if (ClieCaja[i] != null && ClieCaja[i].TiempAtencion == 0) {

ClieCaja = null;

}

if (ClieCaja == null) {

if (PriColaEsper != null) {

Page 95: Ejemplos de Programacion en Java William Loor

ClieCaja[i] = PriColaEsper;

PriColaEsper = PriColaEsper.Sig;

ClieCaja[i].TiempAtencion =

Integer.valueOf(MCTiempAtenc.generar());

ClieCaja[i].HAtencion = Hora;

ClieCaja[i].TEspera = ClieCaja[i].HAtencion - ClieCaja[i].HLlegada;

SumTiempEsper += ClieCaja[i].TEspera;

NoClieAtend += 1;

}

}

}

}

public void CalcularResultados() {

for (int Hora = 0; Hora < TiempAtenBco; Hora++) {

IngresarCliente();

AtenderCliente();

NuevoClie.HLlegada -= 1;

ClieCaja[Hora].TiempAtencion -= 1;

ClieCaja[Hora].TiempAtencion -= 1;

NoClieCola = 0;

cCliente aux;

aux = PriColaEsper;

while (aux != null){

NoClieCola += 1;

aux = aux.Sig;

}

if (NoClieCola > MaxClieCola) ;

MaxClieCola = NoClieCola;

}

}

Page 96: Ejemplos de Programacion en Java William Loor

public void Visualizar(java.awt.List vlb) {

vlb.removeAll();

vlb.add(" Numero de Clientes en la cola = " +

String.valueOf(NoClieCola));

vlb.add(" Numero de Taxis que Salen = " +

String.valueOf(NoClieAtend));

vlb.add(" ------------------------------ ");

vlb.add(" N° Cliente en la Cola Nº de Clientes en la Cola Nº

de Clientes Atendidos ");

cCliente aux = PriColaEsper;

int n = 1;

while (aux != null) {

vlb.add(String.valueOf(n) +" "+ String.valueOf(7 + (int)

(aux.HLlegada / 60))+ ":" + String.valueOf ((int)(aux.HAtencion % 60))+ "

"+ String.valueOf(7 + (int) (aux.HEspera / 60)) + ":" +

String.valueOf((int)(aux.TEspera % 60)));

aux = aux.Sig;

n++;

}

vlb.add(" Nº Máximo de Clientes en la Cola " + String.valueOf((int)

(SumTiempEsper / 60)) + ":" + String.valueOf(MaxClieCola));

}

}


Recommended