Seguidores

viernes, 13 de abril de 2012

Algunos programas hechos en jcreator usando programación orientada a objetos



 PROGRAMAS    

1 PRODUCTOS DE DOS NÚMEROS  
2 PRODUCTO DE DOS NÚMEROS CON DO-WHILE
3 CONVERTIR A DOLARES
4 FACTORIAL 
5 AREAS
6 COMBINACIONES Y PERMUTACIONES
7 PREGUNTAS AL AZAR  DE TABLAS DE MULTIPLICAR
8 FACTORES PRIMOS 
9 ESTADISTICO
10 CUADRATICA
11 PAGO DE LUZ
12 TEMPERATURAS
13 SUMA DE MATRIZ
14 SUMA Y RESTA DE MATRIZ
15 MULTIPLICACION DE MATRIZ
16 MI PRIMER MARCO
17 MI SEGUNDO MARCO 
18 FRAME DE CAMBIO DE MONEDA
19 EDITOR DE TEXTO

Los programas siguientes utilizan esta clase Leer para que funcione, esta clase debe estar en la misma carpeta donde este cada programa. Todos los programas a continuación deben tener esta clase.
Crear este archivo java con el siguiente código:


import java.io.*;

public class Leer{
  public static String dato()  {
    String sdato = "";
    try
    {
      // Definir un flujo de caracteres de entrada: flujoE
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader flujoE = new BufferedReader(isr);
      // Leer. La entrada finaliza al pulsar la tecla Entrar
      sdato = flujoE.readLine();
    }
    catch(IOException e)  {
      System.err.println("Error: " + e.getMessage());
    }
    return sdato; // devolver el dato tecleado
  }
  
  public static short datoShort() {
    try
    {
      return Short.parseShort(dato());
    }
    catch(NumberFormatException e) {
      return Short.MIN_VALUE; // valor más pequeño
    }
  }
  
  public static int datoInt() {
    try  {
      return Integer.parseInt(dato());
    }
    catch(NumberFormatException e)  {
      return Integer.MIN_VALUE; // valor más pequeño
    }
  }
  
  public static long datoLong() {
    try
    {
      return Long.parseLong(dato());
    }
    catch(NumberFormatException e)  {
      return Long.MIN_VALUE; // valor más pequeño
    }
  }
  
  public static float datoFloat()
  {
    try
    {
      return Float.parseFloat(dato());
    }
    catch(NumberFormatException e)
    {
      return Float.NaN; // No es un Número; valor float.
    }
  }
  
  public static double datoDouble() {
    try  {
      return Double.parseDouble(dato());
    }
    catch(NumberFormatException e)   {
      return Double.NaN; // No es un Número; valor double.
    }
  }
}



     1.       PRODUCTOS DE DOS NUMEROS

public class Producto {

    public static void main(String[] args) {
                int valor1=0;
                int valor2=0;
                int resultado=0;


                System.out.println("Dame el primer numero =>"); valor1 = Leer.datoInt();
                               System.out.println("Dame el segundo numero =>"); valor2 = Leer.datoInt();
                               resultado= valor1 * valor2;
                               System.out.println();
                               System.out.println("El resultado es =" + resultado);
    }
}


Dame el primer numero =>
5
Dame el segundo numero =>
8

El resultado es =40
Process completed.




       2.       PRODUCTO DE DOS NUMEROS CON DO-WHILE


public class Productodenumeros {
   
    public static void main(String[] args) {
               
   int valor1=0;
                int valor2=0;
                               int resultado=0;
                                               do {
                                                               System.out.print("Dame el primer numero o <0> para sallir=>"); valor1=Leer.datoInt();
                                               if(valor1!=0)
                                               {
                                               System.out.print("Dame el segundo numero=>");  valor2=Leer.datoInt();              
                                                               resultado=valor1*valor2;
                                                                                              System.out.println();
                                                                                                              System.out.println("El resultado es="+resultado);
                System.out.println();
                                               }
                                               }while(valor1!=0);
                                              
    }
}

--------------------Configuration: <Default>--------------------
Dame el primer numero o <0> para sallir=>3
Dame el segundo numero=>3

El resultado es=9

Dame el primer numero o <0> para sallir=>0
Process completed.



     3.      CONVERTIR A DOLARES

public class Cambiodemoneda{
                public static void main (String[]args){
                               int resp;
                               float cant;
                               double resultado;
                               System.out.println("CANTIDAD A CONVERTIR?");cant=Leer.datoFloat();
                               System.out.println("\n  1)CONVERTIR A PESOS");
                               System.out.println("  2)CONVERTIR A DOLARES");
                               System.out.println("  Escoje la opcion ");resp=Leer.datoInt();
                               if(resp==1)
                               {
                                               resultado=cant*13.00;
                               }
                               else
                               {
                                               resultado=cant/13.00;
                               }
                               System.out.println(".\n\nEL RESULTADO ES "+resultado);
                }
    }


--------------------Configuration: <Default>--------------------
CANTIDAD A CONVERTIR?
2

  1)CONVERTIR A PESOS
  2)CONVERTIR A DOLARES
  Escoje la opcion
1
.
EL RESULTADO ES 26.0
Process completed.





     4.      FACTORIAL

public class Factorial
{
  // Cálculo del factorial de un número
  long fact;
  public static long factorial(int n)
  {
    long fac;
    if (n == 0)
      return 1;
    else
      fac=1;
      do {
       fac=fac*n;
       n=n-1;
      }while (n>1);
      return fac;   
  }

  public static void main(String[] args)
  {
    int numero=0;
    long fact;
    do
    {
      System.out.print("¿Numero a calcular su factorial? ");
      numero = Leer.datoInt();
    }
    while (numero < 0 || numero > 25);
    fact = factorial(numero);
    System.out.println("\nPractica  ");
    System.out.println("Calculo del factorial de un numero ");
    System.out.println("Realizado por: jose");
    System.out.println("\nEl factorial de " + numero + " es: " + fact);
  }
}

--------------------Configuration: <Default>--------------------
¿Numero a calcular su factorial? 8

Practica 
Calculo del factorial de un numero
Realizado por: jose

El factorial de 8 es: 40320
Process completed.



     5.      AREAS

import java.io.PrintStream;
public class Areas {
    public static void main(String[] args)
  {
    int opcion;
    double base, altura, radio, area;
    do
    {         
     System.out.printf("Calculo de areas de figuras geometricas");
     System.out.printf("\n\t 1)AREA DEL CIRCULO");
     System.out.printf("\n\t 2)AREA DEL RECTANGULO");  
     System.out.printf("\n\t 3)AREA DEL TRIANGULO"); 
     System.out.printf("\n\n\t ¿ESCOGE EL AREA A CALCULAR? <0>Salir ");         
     opcion = Leer.datoInt();               
     if (opcion > 0 && opcion<4)     {
                if (opcion==1)
        {
            System.out.printf("\n\n\t ¿VALOR DEL RADIO? ");         
            radio = Leer.datoFloat();       
                area=radio*3.1416;
                System.out.printf("\n El Area es =  %.2f ",area);
                System.out.printf("\n\n");  }
                if (opcion==2)  {
            System.out.printf("\n\n\t ¿VALOR DE LA BASE? ");       
            base = Leer.datoFloat();        
                System.out.printf("\n\n\t ¿VALOR DE LA ALTURA? ");              
            altura = Leer.datoFloat();
                area=base * altura;
                System.out.printf("\n El Area es =  %.2f ",area);
                System.out.printf("\n\n");     }
        if (opcion==3)    {
            System.out.printf("\n\n\t ¿VALOR DE LA BASE? ");       
            base = Leer.datoFloat();        
                System.out.printf("\n\n\t ¿VALOR DE LA ALTURA? ");              
            altura = Leer.datoFloat();
                area=(base * altura)/2;
                System.out.printf("\n El Area es =  %.2f ",area);
        System.out.printf("\nHecho por jose ");
                                               System.out.printf("\n\n");       }                        
      }     
    }while(opcion!=0);               }      
      }
--------------------Configuration: <Default>--------------------
Calculo de areas de figuras geometricas
     1)AREA DEL CIRCULO
     2)AREA DEL RECTANGULO
     3)AREA DEL TRIANGULO
     ¿ESCOGE EL AREA A CALCULAR? <0>Salir 2
     ¿VALOR DE LA BASE? 1
¿VALOR DE LA ALTURA? 1
 El Area es =  1.00







     6.       COMBINACIONES Y PERMUTACIONES

public class CombPerm {
    public static long factorial(int n)
  {
    long fac;
    if (n == 0)
      return 1;
    else
      fac=1;
      do {
       fac=fac*n;
       n=n-1;
      }while (n>1);
      return fac;   
  }
  public static void main(String[] args)
  {
   long ncr, npr, fact,factn, factr, factnr;
   int num=0, rr=0,  numero;
  
   do{
                System.out.print("¿Numero de elementos? "); num = Leer.datoInt();     
    System.out.print("¿De cuanto en cuanto? "); rr = Leer.datoInt();     
   } while (num<rr);
   numero=num;                   factn = factorial(numero);
   numero=num-rr;               factnr = factorial(numero);
   numero=rr;         factr = factorial(numero);
   ncr= factn /(factnr * factr);
   npr= factn / factnr;  
   System.out.println("\nPractica no. 5 ");
   System.out.println("Calculo del no. de combinaciones y permutaciones ");
   System.out.println("Realizado por: jose");
   System.out.println("\nEl no. de Combinaciones es = " + ncr);
   System.out.println("El no. de Permutaciones es = " + npr);
  }
}


--------------------Configuration: <Default>--------------------

¿Numero de elementos? 5
¿De cuanto en cuanto? 3

Practica no. 5
Calculo del no. de combinaciones y permutaciones
Realizado por: jose

El no. de Combinaciones es = 10
El no. de Permutaciones es = 60


     7.      
PREGUNTAS AL AZAR  DE TABLAS DE MULTIPLICAR

import java.io.PrintStream;

public class preguntasalazardetablasdemultiplicar {

  public static void main(String[] args)
  {
                int r=0, resp=0, n1=0, n2=0, b=0, m=0;
   double cal;
    do
    { 
                n1=(int)(Math.random()*10)+1;
               
                n2=(int)(Math.random()*10)+1;
               
                System.out.printf("\n\n\t¿Cuanto es %2d por %2d?<0>Salir   ",n1,n2);
                resp=Leer.datoInt();           
                 if (resp > 0 );
                 {
                                r=n1*n2;
                                if(r==resp)
                                {
                                               b=b+1;
        System.out.printf("\n\n\t CORRECTO!!Llevas %2d BUENAS Y %2d MALAS",b,m);
                                              
      }     
   else
                {
                               m=m+1;
                System.out.printf("\n\n\t INCORRECTO!!Llevas %2d BUENAS Y %2d MALAS",b,m);
                }                                                            
                }
    }while(resp!=0);
   
    cal=b*100/(b+m);
   
                System.out.printf("\n\n\t CALIFICACION = %.2f",cal);
  }
}

--------------------Configuration: <Default>--------------------
    ¿Cuanto es 10 por  9?<0>Salir   90


     CORRECTO!!Llevas  1 BUENAS Y  0 MALAS

    ¿Cuanto es  1 por  8?<0>Salir   0



     8.      FACTORES PRIMOS


public class Factoresprimos {   
    public static void main(String[] args) {
                long numero,r,d,prueba;
      System.out.println("Numero a factorizar "); numero = Leer.datoLong();
    d = 2;
    do    {
                r = numero / d;
                if ((numero%d)==0)             {
                               System.out.print(d +" x ");
                               numero= r;         } 
                else         {
                               d=d +1;                  }
    }          while (r>1);           
                System.out.print(" 1 ");
    }
                }

--------------------Configuration: <Default>--------------------

Programa corrido
Numero a factorizar
150
2 x 3 x 5 x 5 x  1
Process completed.




     9.     ESTADISTICO

import java.lang.Math.*;
public class Estadistica   {
  public static void main(String[] args)  {
    int nElementos, b, guarda, suma,dos=2;
    double prom, sumaV, vza, v; //, dos=2.0;
    System.out.println("Programacion Orientada a Objetos ");
    System.out.println("Programa de Calculos Estadisticos: ");
    System.out.println("Nombre: jose ");
    System.out.println();
    System.out.print("¿Cuantos elementos son?: ");
    nElementos = Leer.datoInt();
    int[] m = new int[nElementos];
    int i = 0;
    suma=0;
    System.out.println("Introduce los datos a calcular.");
    for (i = 0; i < nElementos; i++)    {
      System.out.print("Elemento[" + i + "] = ");
      m[i] = Leer.datoInt();
      suma=suma+m[i];    }
    do {   
                b=0;
                for(i=0;i<nElementos-1;i++)               {
                                               if (m[i] > m[i+1])  {
                                               guarda=m[i];
                                               m[i]=m[i+1];
                                               m[i+1]=guarda;
                                               b=1;        }   }         
    }while (b==1);
    System.out.println();
    System.out.print("Dado los datos:  ");
    for (i = 0; i < nElementos; i++)
      System.out.print(m[i] + " ");
    System.out.println(); 
    prom=suma/nElementos;             
    System.out.println("Su promedio es: " + prom);
    System.out.println("El valor minimo es: " + m[0]);
    System.out.println("El valor maximo es: " + m[nElementos-1]);
    sumaV=0;
    for (i = 0; i < nElementos; i++)   {
                v=(Math.pow((m[i] -prom), dos));
                sumaV=sumaV+ v;    }
    vza=sumaV / nElementos - 1;
    System.out.println("Su Varianza es: " + vza);
    System.out.println("Su DesvStd es: " + Math.sqrt(vza));        
    System.out.println("\n\nFin del proceso.");           }
}    --------------------Configuration: <Default>----------------
Programacion Orientada a Objetos
Programa de  Calculos Estadisticos:
Nombre: jose
¿Cuantos elementos son?: 5
Introduce los datos a calcular.
Elemento[0] = 3               Dado los datos:  3 4 4 5 6
Elemento[1] = 4               Su promedio es: 4.0
Elemento[2] = 6               Su promedio es: 4.0
Elemento[3] = 5               El valor minimo es: 3
Elemento[4] = 4               El valor maximo es: 6
Su Varianza es: 0.19999999999999996
Su DesvStd es: 0.44721359549995787
Fin del proceso.
Process completed.




     10  CUADRATICA

import java.io.PrintStream;

public class Cuadratica {
   
    public static void main(String[] args) {
   
    double a, b, c, d, r1, r2;
       
    do
    {
      System.out.print("¿Valor del coeficiente A? "); a = Leer.datoDouble();
    } while (a==0);     
      PrintStream fs = System.out;                     
      System.out.print("¿Valor del coeficiente B? "); b = Leer.datoDouble();
      System.out.print("¿Valor del coeficiente C? "); c = Leer.datoDouble();
      d= b*b - 4*a*c;
      if (d<0)  {
                                               System.out.println(" No hay Solucion...");                                    
      }
      else
      {                       
                               r1= (-b + Math.sqrt(d))/(2*a);
                               r2= (-b - Math.sqrt(d))/(2*a);
                               fs.printf("\n Dada: %.0f xª %.0f x + %.0f ===> ",a,b,c);
                               fs.printf(" x1 = %.2f      x2 = %.2f", r1,r2);
      }
  }                             
}

--------------------Configuration: <Default>--------------------

¿Valor del coeficiente A? 1
¿Valor del coeficiente B? -7
¿Valor del coeficiente C? 2

 Dada: 1 xª -7 x + 2 ===>  x1 = 6.70      x2 = 0.30

¿Valor del coeficiente A? 1
¿Valor del coeficiente B? 2
¿Valor del coeficiente C? 2
 No hay Solucion...

¿Valor del coeficiente A? 1
¿Valor del coeficiente B? -7
¿Valor del coeficiente C? 12

 Dada: 1 xª -7 x + 12 ===>  x1 = 4.00      x2 = 3.00



     11.   PAGO DE LUZ

import java.io.PrintStream;
public class Pago_luz {   
    public static void main(String[] args)  {
    int numero=0; int kw=0;  double pk, importe, iva, total;
    do   {                 
      System.out.print("¿Numero de Medidor? <0>Salir “)
      numero = Leer.datoInt();
         if (numero > 0)   {
                System.out.print("¿Kilowatts consumidos? ");
        kw = Leer.datoInt();
        if (kw<=300)   {
                pk=0.30;    }
        else if (kw>300 && kw<=500)     {
                pk=0.70;     }
        else pk=1.50;
        importe=kw*pk;
        iva=importe * 0.16;
        total=importe+iva;
        System.out.printf("\nNumero de Medidor "+numero);
        System.out.printf("\nKiloWatts consumidos "+kw);System.out.printf("\tPrecio del Kilowatt %.2f ",pk);
        System.out.printf("\n\n  Importe a pagar $ %.2f ",importe);
        System.out.printf("\n      Iva a pagar $ %.2f ",iva);
        System.out.printf("\n---------------------------------");
        System.out.printf("\n    Total a pagar $ %.2f ",total);
          System.out.printf("\n\nHecho por jose");
        System.out.printf("\n\n");  }     
    }while(numero!=0);  } }

CORRIDA DEL PROGRAMA
¿Numero de Medidor? <0>Salir 7
¿Kilowatts consumidos? 66
Numero de Medidor 7
KiloWatts consumidos 66 Precio del Kilowatt 0.30
  Importe a pagar $ 19.80
      Iva a pagar $ 3.17
---------------------------------
    Total a pagar $ 22.97
Hecho por jose
¿Numero de Medidor? <0>Salir 0
Process completed.



     12.   TEMPERATURAS

import java.io.PrintStream;

class Temperaturas {
                 PrintStream fs = System.out;
               
                public static void main(String args[]) {
                               int vi=0;
                    int vf=0;
                    int c=0;
                    float k=0.0F, f=0.0F, r=0.0F;
                              
                               System.out.print("Desde que valor quieres? => ");  vi = Leer.datoInt();
        System.out.print("Hasta que valor quieres? => ");  vf = Leer.datoInt();
       
        PrintStream fs = System.out;
        fs.printf("TABLA DE CONVERSION DE TEMPERATURAS\n");
        fs.printf("Realizado por: jose \n");
        fs.printf("Centigrados  Kelvin     Farenheit  Rankin\n");
        for (c=vi;c<=vf;c++) {
                k=c+273;
                f=1.8F * c + 32  ;
                r= f +460;
                fs.printf("%8d     %.2f      %.2f     %.2f\n", c,k,f,r );
        }                     
                }
}

--------------------Configuration: <Default>--------------------
Desde que valor quieres? => 5
Hasta que valor quieres? => 12
TABLA DE CONVERSION DE TEMPERATURAS
Realizado por: jose
Centigrados    Kelvin     Farenheit  Rankin
       5       278.00      41.00     501.00
       6       279.00      42.80     502.80
       7       280.00      44.60     504.60
       8       281.00      46.40     506.40
       9       282.00      48.20     508.20
      10     283.00      50.00     510.00
      11     284.00      51.80     511.80
      12     285.00      53.60     513.60

13   SUMA DE MATRIZ

public class SumaMatriz {
  
   // USO DE ARREGLOS BIDIMENSIONALES EN MULTIPLICACION DE MATRICES
  public static void main(String[] args)
  {
    int i, j, nfa,nca, nfb, ncb, k, suma;
    System.out.println("Programacion Orientada a Objetos ");
    System.out.println("Programa de Arreglo bidimensional: ");
    System.out.println("hecho por: jose ");
    System.out.println();
    do{
    System.out.print("Cuantas filas tiene la matriz A: "); nfa = Leer.datoInt();
    System.out.print("Cuantas columnas tiene la matriz A: "); nca = Leer.datoInt();
    System.out.print("Cuantas filas tiene la matriz B: "); nfb = Leer.datoInt();
    System.out.print("Cuantas columnas tiene la matriz B: "); ncb = Leer.datoInt();
    }while(nca!=nfb);
    int a[][] = new int[nfa+1][nca+1]; // crear la matriz a
    int b[][] = new int[nfb+1][ncb+1]; // crear la matriz b
    int c[][] = new int[nfa+1][ncb+1]; // crear la matriz c   
    System.out.println("Introducir los valores de las matrices.");
   
    for (i = 1; i <= nfa; i++)     {
      for (j=1; j<=nca;j++)    {
       System.out.print("a["+i+"]["+j+"] = "); a[i][j] = Leer.datoInt();
      }
    }
    for (i = 1; i <= nfb; i++)     {
      for (j=1; j<=ncb;j++)    {
       System.out.print("b["+i+"]["+j+"] = "); b[i][j] = Leer.datoInt();
      }
    }
      for (i = 1; i <= nfa; i++)     {
      for (j=1; j<=ncb;j++)      {
      suma=0;
       for (k=1;k<=nca;k++)  {
          suma=suma+ a[i][k]*b[k][j];
       }
       c[i][j]=suma;
      }
    }
       
    // Visualizar los elementos de la matriz resultante
     System.out.print(" \nMatriz Resultante :");
     System.out.print("\t \t");
     for (i=1;i<=nfa;i++)   {
      System.out.println("");   
      for(j=1;j<=ncb;j++)   {
          System.out.print(c[i][j]);             System.out.print("   ");                         
      }
     }         
  }
}


14.  SUMA Y RESTA DE MATRIZ

public class SumaYrestadeMatriz
{   
    public static void main(String[] args)
                {
                int  i, j, nf, nc, resp;
                    System.out.println("programacion orientada a objetos");
                System.out.println("programa de arreglo bidimensional");
                               System.out.println ("jose");
                               System.out.println();
                               System.out.print("cuantas filas tienen las matrices----->"); nf= Leer.datoInt();
                               System.out.print("cuantas columnas tienen las matrices-->");nc= Leer.datoInt();
                               System.out.print("va a ser (1) suma o (2) resta de matrices-->"); resp= Leer.datoInt();
                               int a [][] = new int [nf+1][nc+1]; //crear matriz a
                               int b [][] = new int [nf+1][nc+1];//crear la matriz b
                               int c [][] = new int [nf+1][nc+1]; //crear la matriz c
                              
                               System.out.println ("introduce los valores de las matrices");
               
                               for (i=1; i<=nf; i++)
                               {
                               for(j=1; j<=nc; j++)
                               {
                               System.out.print("a ["+1+"] ["+j+"]="); a[i][j]= Leer.datoInt();
                               System.out.print("b ["+1+"] ["+j+"]="); b[i][j]= Leer.datoInt();
                               if(resp==1)
                                               c[i][j]= a[i][j]+b[i][j];
                                               else
                                               c[i][j]= a[i][j]-b[i][j];                             }
                               }
                               //visualizar los elementos de la matriz resultante
                               System.out.print("\n matriz suma:");
                              
                               for(i=1; i<=nf;i++)
                               {
                               System.out.println("");
                               for (j=1; j<=nc; j++)
                               {
                               System.out.println(a[i][j]);System.out.print("");
                               }
                               System.out.print("\t\t");
                               for(j=1; j<=nc;j++)
                               {
                               System.out.print(b[i][j]); System.out.print("");
                               }
                               System.out.print("\t\t\t");
                               for (j=1; j<=nc;j++)
                               {
                               System.out.print(c[i][j]); System.out.print("");
                               }
                               }
    }
}



15. MULTIPLICACION DE MATRIZ

public class Sumamatriz {
  public static void main(String[] args)  {
    int i, j, nfa,nca, nfb, ncb, k, suma;
    System.out.println("Programacion Orientada a Objetos ");
    System.out.println("Programa no. 8 Arreglo bidimensional: ");
    System.out.println("Nombre: jose ");
    System.out.println();
    do{
    System.out.print("Cuantas filas tiene la matriz A: "); nfa = Leer.datoInt();
    System.out.print("Cuantas columnas tiene la matriz A: "); nca = Leer.datoInt();
    System.out.print("Cuantas filas tiene la matriz B: "); nfb = Leer.datoInt();
    System.out.print("Cuantas columnas tiene la matriz B: "); ncb = Leer.datoInt();
    }while(nca!=nfb);
    int a[][] = new int[nfa+1][nca+1]; // crear la matriz a
    int b[][] = new int[nfb+1][ncb+1]; // crear la matriz b
    int c[][] = new int[nfa+1][ncb+1]; // crear la matriz c
    System.out.println("Introducir los valores de las matrices.");
    for (i = 1; i <= nfa; i++)     {
      for (j=1; j<=nca;j++)    {
       System.out.print("a["+i+"]["+j+"] = "); a[i][j] = Leer.datoInt();      }    }
    for (i = 1; i <= nfb; i++)     {
      for (j=1; j<=ncb;j++)    {
       System.out.print("b["+i+"]["+j+"] = "); b[i][j] = Leer.datoInt();      }
    }
    for (i = 1; i <= nfa; i++)     {
      for (j=1; j<=ncb;j++)      {  
 suma=0;
       for (k=1;k<=nca;k++)  {
          suma=suma+ a[i][k]*b[k][j];     }
       c[i][j]=suma;       }
    }  
    // Visualizar los elementos de la matriz resultante
     System.out.print(" \nMatriz Resultante :");
     System.out.print("\t \t");
     for (i=1;i<=nfa;i++)   {
      System.out.println("");
      for(j=1;j<=ncb;j++)   {
          System.out.print(c[i][j]);          System.out.print("   ");          }
     }            }       }
--------------------Configuration: <Default>--------------------
Programacion Orientada a Objetos
Programa no. 8 Arreglo bidimensional:
Nombre: jose
Cuantas filas tiene la matriz A: 2
Cuantas columnas tiene la matriz A: 2
Cuantas filas tiene la matriz B: 2
Cuantas columnas tiene la matriz B: 2
Introducir los valores de las matrices.
a[1][1] = 1                  Matriz Resultante :    
a[1][2] = 1                  4   3  
a[2][1] = 2                  8   6  
a[2][2] = 2                  Process completed.
b[1][1] = 2
b[1][2] = 2
b[2][1] = 2
b[2][2] = 1



16. MI PRIMER MARCO

import java.awt.*;
class MiPrimerMarco extends Frame  {
    private static final int ANCHO_MARCO = 300;
    private static final int ALTO_MARCO = 200;
    private static final int ORIGEN_X_MARCO = 150;
    private static final int ORIGEN_Y_MARCO = 250;
   
    public MiPrimerMarco()  {
                setSize(ANCHO_MARCO,ALTO_MARCO);
                setResizable(false);
                setTitle("PROGRAMA: MI PRIMER MARCO");
                setLocation(ORIGEN_X_MARCO,ORIGEN_Y_MARCO);
    }
class PruebaMiPrimerMarco {             
    public static void main(String[] args) {      
        MiPrimerMarco marco = new MiPrimerMarco();
        marco.setVisible(true);
        }
}


17. MI SEGUNDO MARCO

import java.awt.*;
import java.awt.event.*;
class MiQuintoMarco extends Frame implements ActionListener
{
/******************
   Data Members
******************/
   private static final int ANCHO_MARCO    = 300;
   private static final int ALTO_MARCO     = 200;
   private static final int ORIGEN_X_MARCO = 150;
   private static final int ORIGEN_Y_MARCO = 250;
   private static final int BUTTON_WIDTH  = 60;
   private static final int BUTTON_HEIGHT = 30;
   Button botonCancelar, botonOK;
   TextField lineaEntrada;
/******************
   Constructor
******************/
   public MiQuintoMarco()
   {
      // establecer las propiedades del marco
      setSize      (ANCHO_MARCO, ALTO_MARCO);
      setResizable (false);
      setTitle     ("Programa MiQuintoMarco");
      setLocation  (ORIGEN_X_MARCO, ORIGEN_Y_MARCO);
      setLayout    (null);
      // crear y colocar dos botones en el marco
      botonOK = new Button("OK");
      botonOK.setBounds(100, 150, BUTTON_WIDTH, BUTTON_HEIGHT);
      add(botonOK);
      botonCancelar = new Button("CANCELAR");
      botonCancelar.setBounds(170, 150, BUTTON_WIDTH, BUTTON_HEIGHT);
      add(botonCancelar);
      // registrar este marco como un escuchador de acciones de los
      // dos botones
      botonCancelar.addActionListener(this);
      botonOK.addActionListener(this);
      lineaEntrada = new TextField();
            lineaEntrada.setBounds(90, 50, 130, 25);
      add(lineaEntrada);
      lineaEntrada.addActionListener(this);
      // registrar un objeto ProgramaTerminador como escuchador de ventana
class ProgramaTerminador implements WindowListener{
                public void windowClosing (WindowEvent evento)
                {
                               System.exit(0);                    
                }
                public void windowActivated (WindowEvent evento) {}
                public void windowClosed (WindowEvent evento) {}
                public void windowDeactivated (WindowEvent evento) {}                        
    public void windowDeiconified (WindowEvent evento) {}
    public void windowIconified (WindowEvent evento) {}
    public void windowOpened (WindowEvent evento) {}                           
}
      // de este marco
      addWindowListener(new ProgramaTerminador());
   }
/*******************************************
      Tratamiento de eventos de acciones
*******************************************/
   public void actionPerformed(ActionEvent evento) {
      if (evento.getSource() instanceof Button) {
         Button botonPulsado = (Button) evento.getSource();
         if (botonPulsado == botonCancelar) {
            setTitle("Ha pulsado CANCELAR");
         }
         else { // la fuente del evento debe de ser botonOk
            setTitle("Ha pulsado OK");
         }
      }
      else { // la fuente del evento es lineaEntrada
         setTitle("Ha introducido '" + lineaEntrada.getText() + "'");
      }  
   }
}
class PruebaQuintoMarco  {             
    public static void main(String[] args) {      
        MiQuintoMarco marco = new MiQuintoMarco();
        marco.setVisible(true);
        }
}




18. FRAME DE CAMBIO DE MONEDA

import java.awt.*;
import java.awt.event.*;

class Dolares2 extends Frame implements ActionListener{
private static final int ANCHO_MARCO=500;
private static final int ALTO_MARCO=300;
private static final int ORIGEN_X_MARCO=150;
private static final int ORIGEN_Y_MARCO=300;
private static final int BUTTON_WIDTH=90;
 private static final int BUTTON_HEIGHT=30;
                Button botonSalir,botonCalc;
                TextField valorDato, resultado, paridad;
                Label cantidad, paridLbl;
 public Dolares2() {
                setSize (ANCHO_MARCO, ALTO_MARCO);
                setResizable(false);
                setTitle ("CONVERSION DE MONEDA");
                setLocation (ORIGEN_X_MARCO, ORIGEN_Y_MARCO);
                setBackground(Color. CYAN);
                setLayout (null);
                botonCalc=new Button ("CALCULAR");
                botonCalc.setBounds(100,200,BUTTON_WIDTH,BUTTON_HEIGHT);
                add(botonCalc);
                botonSalir=new Button ("SALIR");
                botonSalir.setBounds(350,200,BUTTON_WIDTH,BUTTON_HEIGHT);
                add(botonSalir);
                Label cantidad=new Label("CUANTOS DOLARES SON");
                cantidad.setBounds(100,50,200,25);
                add(cantidad);
               
                Label paridLbl=new Label("Valor actual del dolar");
                paridLbl.setBounds(100,75,200,25);
                add(paridLbl);
               
                botonSalir.addActionListener(this);
                botonCalc.addActionListener(this);
                valorDato=new TextField();
                valorDato.setBounds(300, 50, 100, 25);
                add(valorDato);
               
                valorDato.addActionListener(this);
                paridad=new TextField();
                paridad.setText("14.50");
                paridad.setBounds(300,75,100,25);
    add(paridad);
    resultado= new TextField();
    resultado.setBounds(150,150,200,25);
    resultado.setVisible(false);
    add(resultado);
   
    addWindowListener(new ProgramaTerminador());
  }
                public void actionPerformed(ActionEvent evento) {
                               double cant;
                               double parid;
                              
                               if(evento.getSource()instanceof Button){
                                               Button botonPulsado=(Button) evento.getSource();
                                              
                                               if(botonPulsado==botonSalir) {
                                                               System.exit(0);
                                               }
                                               if(botonPulsado==botonCalc){
                                                               cant=Double.parseDouble(valorDato.getText());
                                                               parid=Double.parseDouble(paridad.getText());
                                                               resultado.setVisible(true);
                resultado.setText("Resultado="+Double.toString(cant*parid));
                                               }
                                               }
                                               else{                       cant=Double.parseDouble(valorDato.getText());
                                                               parid=Double.parseDouble(paridad.getText());
                                                               resultado.setVisible(true);
                resultado.setText("Resultado="+Double.toString(cant*parid));
                                               }             
                }
                }
                class ProgramaTerminador implements WindowListener {
                               public void WindowClosing(WindowEvent evento) {
                                               System.exit(0);   }

               
               
                 public void windowActivated(WindowEvent evento){}
                 public void windowClosed(WindowEvent evento){}
                 public void windowDeactivate(WindowEvent evento){}            
                 public void windowDeiconified(WindowEvent evento){}
                 public void windowIconified(WindowEvent evento){}
                 public void windowOpened(WindowEvent evento){} 
                }
                 class PruebaDolares
                                {
    public static void main(String [] args) {
                Dolares2 marco=new Dolares2();
                marco.setVisible(true);
    }
    }



19. EDITOR DE TEXTO

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;

class menu extends JFrame {
                private int tamaño=17;
                private JTextArea areaTexto;
                private JButton cor,cop,peg,nue,gua,ab,acerca,ayuda;
                private JScrollPane scroll;
                private JComboBox tFuente;
                private Font areaFuente;

                public menu () {
                               super("Editor de textos hecho por jose");
                               try {
                                               UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                               }
                               catch (Exception e) {
                                               JOptionPane.showMessageDialog(null,"Error al intentar cargar L&F");
                               }
                               areaFuente= new Font("Arial", Font.PLAIN, tamaño);
                               areaTexto= new JTextArea();
                               areaTexto.setFont(areaFuente);
                               menus ();
                               barra();
                               scroll= new JScrollPane(areaTexto);
                               getContentPane().add(scroll,BorderLayout.CENTER);
                               JPanel panel= new JPanel();
                               JPanel panel1= new JPanel();
                               JPanel panel2= new JPanel();
                               panel.setBackground(Color.lightGray);
                               panel1.setBackground(Color.lightGray);
                               panel2.setBackground(Color.lightGray);
                               getContentPane().add(panel,BorderLayout.SOUTH);
                               getContentPane().add(panel1,BorderLayout.WEST);
                               getContentPane().add(panel2,BorderLayout.EAST);
                               setSize(800,580);
                               setVisible(true);
                               show ();
                }
                public void menus () {
                               JMenuBar menus = new JMenuBar();
                               JMenu archivo= new JMenu("Archivo");
                               JMenuItem nue= new JMenuItem("Nuevo", new ImageIcon("images/hoja_6.gif"));
                               nue.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              nuevo();
                                                               }
                                               }  );                           
                               JMenuItem sal= new JMenuItem("Salir",new ImageIcon("images/salir.gif"));
                               sal.addActionListener(
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                         String d=JOptionPane.showInputDialog("Desea salir y guardar el archivo S/N");
                                                                              if (d.equals("s")) {
                                                                                              guardar();
                                                                                              System.exit(0);
                                                                              }
                                                                              else if(d.equals("n")) {
                                                                                              System.exit(0);
                                                                              }
                                                                              else {
                                                                                              JOptionPane.showMessageDialog(null,"Caracter invalido");
                                                                              }
                                                               }  }     );                                                                   
                               JMenuItem abr= new JMenuItem("Abrir",new ImageIcon("images/libro_1.gif"));
                               abr.addActionListener(
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              abrir ();
                                                               }    }    );                                                                 
                               JMenuItem guar= new JMenuItem("Guardar",new ImageIcon("images/guardar.gif"));
                               guar.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              guardar ();
                                                               }   }    );                                                                   
                               JMenu editar= new JMenu("Editar");
                               JMenuItem cor= new JMenuItem("Cortar", new ImageIcon("images/cut.gif"));
                               cor.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              cortar ();
                                                               }   }    );                                                                      
                              JMenuItem cop= new JMenuItem("Copiar",new ImageIcon("images/copiar_0.gif"));
                               cop.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              copiar ();
                                                               }   }    );                                                                    
                               JMenuItem peg= new JMenuItem ("Pegar",new ImageIcon("images/paste.gif"));
                               peg.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              pegar ();
                                                               }   }   );                                                                    
                              JMenuItem fuen= new JMenuItem("Tamaño de fuente",new ImageIcon("images/hoja_2.gif"));
                               fuen.addActionListener(
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              tamaño_f();
                                                               }  }   );                                                                        
                               JMenu about= new JMenu("Ayuda");
                               JMenuItem ayu= new JMenuItem("Ayuda",new ImageIcon("images/bombillo.gif"));
                               ayu.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              ayuda ();
                                                               }     }  );                                                                   
                               JMenuItem acer= new JMenuItem("Acerca de...",new ImageIcon("images/chulo.gif"));
                               acer.addActionListener(
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              acerca();
                                                               }  }   );                         
                               archivo.add(nue);
                               archivo.add(sal);
                               archivo.addSeparator();
                               archivo.add(abr);
                               archivo.add(guar);
                               editar.add(cor);
                               editar.add(cop);
                               editar.add(peg);
                               editar.addSeparator();
                               editar.add(fuen);
                               about.add(ayu);
                               about.add(acer);
                               menus.add(archivo);
                               menus.add(editar);
                               menus.add(about);
                               setJMenuBar(menus);
                }
                public void barra () {
                               JToolBar barras= new JToolBar();
                               nue= new JButton ();
                               nue.setIcon(new ImageIcon("images/hoja_6.gif"));
                               nue.setMargin(new Insets(3,0,0,0));
                               nue.setToolTipText("Nuevo");
                               nue.addActionListener(
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              nuevo ();
                                                               }    }   );                                                            
                               barras.add(nue);
                               ab= new JButton();
                               ab.setIcon(new ImageIcon("images/libro_1.gif"));
                               ab.setMargin(new Insets(2,0,0,0));
                               ab.setToolTipText("Abrir");
                               ab.addActionListener(
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              abrir ();
                                                               }    }   );
                               barras.add(ab);
                               gua= new JButton();
                               gua.setIcon(new ImageIcon("images/guardar.gif"));
                               gua.setMargin(new Insets(2,0,0,0));
                               gua.setToolTipText("Guardar");
                               gua.addActionListener(
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              guardar ();
                                                               }   }   );
                               barras.add(gua);
                               barras.addSeparator();
                               cor= new JButton();
                               cor.setIcon(new ImageIcon("images/cut.gif"));
                               cor.setMargin(new Insets(2,0,0,0));
                               cor.setToolTipText("Cortar");
                               cor.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              cortar ();
                                                               }   }  );
                              barras.add(cor);
                               cop= new JButton();
                               cop.setIcon(new ImageIcon("images/copiar_0.gif"));
                               cop.setMargin(new Insets(-3,0,0,0));
                               cop.setToolTipText("Copiar");
                               cop.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              copiar ();
                                                               }  }  );
                               barras.add(cop);
                               peg= new JButton();
                               peg.setIcon(new ImageIcon("images/paste.gif"));
                               peg.setMargin(new Insets(2,0,0,0));
                               peg.setToolTipText("Pegar");
                               peg.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              pegar ();
                                                               }  }  );
                               barras.add(peg);
                               JButton del= new JButton();
                               del.setIcon(new ImageIcon("images/borrador.gif"));
                               del.setMargin(new Insets(2,0,0,0));
                               del.setToolTipText("BORRAR todo el texto");
                               del.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              areaTexto.setText("");
                                                               }  }    );
                               barras.add(del);
                               barras.addSeparator();
                               ayuda= new JButton();
                               ayuda.setIcon(new ImageIcon("images/bombillo.gif"));
                               ayuda.setMargin(new Insets(2,0,0,0));
                               ayuda.setToolTipText("Ayuda");
                               ayuda.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              ayuda ();
                                                               }    }  );
                               barras.add(ayuda);
                               acerca= new JButton();
                               acerca.setIcon(new ImageIcon("images/chulo.gif"));
                               acerca.setMargin(new Insets(5,2,0,0));
                               acerca.setToolTipText("Acerca de...");
                               acerca.addActionListener (
                                               new ActionListener () {
                                                               public void actionPerformed (ActionEvent e) {
                                                                              acerca ();
                                                               }    }   );
                               barras.add(acerca);
                               barras.addSeparator();
                               tFuente= new JComboBox();
                               tFuente.addItem("Tamaño Fuente");
                               tFuente.addItem("10");
                               tFuente.addItem("20");
                               tFuente.addItem("30");
                               tFuente.addItem("40");
                                tFuente.addItem("50");
                               tFuente.addItem("Personalizar");
                               tFuente.setToolTipText("Tamaño de fuente");
                               tFuente.addItemListener(
                                               new ItemListener () {
                                                               public void itemStateChanged(ItemEvent e) {
                                                                              int elegido;
                                                                              elegido=tFuente.getSelectedIndex();
                                                                              switch (elegido) {
                                                                                              case 1:
                                                                                                              areaFuente= new Font("Arial", Font.PLAIN, 10);
                                                                                                              areaTexto.setFont(areaFuente);
                                                                                                              break;
                                                                                             case 2:
                                                                                                              areaFuente= new Font("Arial", Font.PLAIN, 20);
                                                                                                              areaTexto.setFont(areaFuente);
                                                                                                              break;
                                                                                              case 3:
                                                                                                              areaFuente= new Font("Arial", Font.PLAIN, 30);
                                                                                                              areaTexto.setFont(areaFuente);
                                                                                                              break;
                                                                                              case 4:
                                                                                                              areaFuente= new Font("Arial", Font.PLAIN, 40);
                                                                                                              areaTexto.setFont(areaFuente);
                                                                                                              break;
                                                                                              case 5:
                                                                                                              areaFuente= new Font("Arial", Font.PLAIN, 50);
                                                                                                              areaTexto.setFont(areaFuente);
                                                                                                              break;
                                                                                              case 6:                                                                                                         tamaño=Integer.parseInt(JOptionPane.showInputDialog("Digite el tamaño de la fuente"));
                                                                                                              areaFuente= new Font("Arial", Font.PLAIN, tamaño);
                                                                                                              areaTexto.setFont(areaFuente);
                                                                                                              break;
                                                                              }   }    }    );                                                             
                               barras.add(tFuente);
                               barras.addSeparator();
                               getContentPane().add(barras,BorderLayout.NORTH);   {            
                public void nuevo () {
                               new menu ();   }             
                public void abrir () {
                               JFileChooser fileChooser = new JFileChooser();
                               fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                               int result= fileChooser.showOpenDialog(this);
                               if (result== JFileChooser.CANCEL_OPTION) return;
                               File name= fileChooser.getSelectedFile();
                               if(name.exists()) {
                                               if (name.isFile()) {
                                                               try {
                                                                              BufferedReader input= new BufferedReader(new FileReader (name));
                                                                              StringBuffer buffer= new StringBuffer();
                                                                              String text;
                                                                              areaTexto.setText("");
                                                                              while ((text=input.readLine()) !=null)
                                                                               buffer.append(text+ "\n");
                                                                              areaTexto.append(buffer.toString());    }   catch (IOException ioException) {                                                                                                                 
    JOptionPane.showMessageDialog(null,"Error en el archivo", "Error",JOptionPane.ERROR_MESSAGE);
                                                               }  }                                           
                                               else if (name.isDirectory ()) {
                                                               String directory[] = name.list();
                                                               areaTexto.append("\n\nContenido del directorio:\n");
                                                               for (int i=0;i<directory.length; i++)
                                                                              areaTexto.append(directory [i]+"\n");    }                                          
                                               else {
 JOptionPane.showMessageDialog(null," No existe "," Error ",JOptionPane.ERROR_MESSAGE);
                                               }     }     }                 
                public void guardar () {
                               JOptionPane.showMessageDialog(null,"¡Por favor no olvide colocar la extension del archivo (*.txt)!");
                               JFileChooser fileChooser = new JFileChooser();
                               fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                               int result= fileChooser.showSaveDialog(this);
                               if (result== JFileChooser.CANCEL_OPTION) return;
                                               File name= fileChooser.getSelectedFile();
                                               try {
                                                               PrintWriter output= new PrintWriter(new FileWriter( name));
                                                               output.write(areaTexto.getText());
                                                               output.close();
                                               }
                                               catch (IOException ioException) {
JOptionPane.showMessageDialog(null,"Error en el archivo","Error",JOptionPane.ERROR_MESSAGE);   }    }                                                    
                public void cortar () {
                               areaTexto.cut();
                }
                public void copiar () {
                               areaTexto.copy();
                }
                public void pegar () {
                               areaTexto.paste();
                }
                public void ayuda () {
                               JOptionPane.showMessageDialog(null," Nuevo: Abre una nueva ventana\n Abrir: Abre un documento existente\n Guardar: Guarda el documento\n Salir: Salir del programa\n Cortar: ctrl+x\n Copiar: ctrl+c\n Pegar: ctrl+v\n Salir sin guardar: alt+F4");
                }
                public void tamaño_f () {
                               tamaño=Integer.parseInt(JOptionPane.showInputDialog("Digite el tamaño de la fuente"));
                               areaFuente= new Font("Arial", Font.PLAIN, tamaño);
                               areaTexto.setFont(areaFuente);
                }
                public void acerca () {
                               JOptionPane.showMessageDialog(null,"Editor de textos\nDesarrollado por:  jose\n");
                }
                public static void main (String []args) {
                               JOptionPane.showMessageDialog(null,"Para el correto funcionamiento del programa procure\nabrir solo archivos de tipo *.txt");
                               new menu();
                }
}

DESCARGAR AQUÍ LOS PROGRAMAS: