martes, 22 de abril de 2014

Depreciacion del coche C#

using System;
utilizando System.Collections.Generic;
utilizando System.Linq;
utilizando System.Text;
utilizando System.Threading.Tasks;

DepreciacionCoche espacio de nombres
{
    class Program
    {
        static void Main (string [] args)
        {

            Console.Title = "JOSUE SANTANA ";
            int Costo, vidautil, valorRecuperacion;
            int depreciacion, valorInicialAño = 1;
            int depreciacionAcumulada;
            int valorAnual;

            Console.WriteLine ("introducir el Costo:");
            Costo = Convert.ToInt32 (Console.ReadLine ());

            Console.WriteLine ("introducir la vida util:");
            vidautil = Convert.ToInt32 (Console.ReadLine ());

            Console.WriteLine ("introducir el valor de recuperacion:");
            valorRecuperacion = Convert.ToInt32 (Console.ReadLine ());

            depreciacion = (Costo - valorRecuperacion) / vidautil;

            / / DepreciacionAcumulada = valorInicialAño * depreciacion;

           

            mientras que (valorInicialAño <= vidautil)
            {
               
                depreciacionAcumulada = valorInicialAño * depreciacion;
                valorAnual = costo-depreciacionAcumulada;
                Console.WriteLine ("Año:" + + valorInicialAño "depreciacion:" + + depreciacion "Acumulada depreciacion:"
                    + DepreciacionAcumulada + "valor anual:" + valorAnual);


                valorInicialAño + +;

            }



            Console.Write ("Pulse cualquier tecla para continuar ...");
            Console.ReadKey (true);
        }
    }
}

QuickSort generico en java


package ejemploquicksort;
import java.util.*;

public class EjemploQuickSort {

    public static void main(String[] args) {
 
        int[] arreglo={2,55,6,5,7,8,44,22,11,2,8,783};
         System.out.println("arreglo desordenado ");
       
         for(int i=0;i<arreglo.length;i++)
         {
          System.out.print(arreglo[i]+",");
       
         }
         System.out.println();
         Arrays.sort(arreglo);
       
          System.out.println("arreglo ordenado ");
         for(int i=0;i<arreglo.length;i++)
         {
          System.out.print(arreglo[i]+",");
       
         }
    }
}

Ejemplo BufferReader Java


package ejemplobufferedreader;
import java.io.*;
/**
 *
 * @author JOSUE
 */
public class EjemploBufferedReader {

    public static void main(String[] args) {
       
        throws IOException
               
                {
                    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                   
                    String str;
                   
                    System.out.println("Introduzca texto");
                    System.out.println("Introduzca ´stop´ para finalizar");
                }
               
                do{
                   
                    str=br.redLine();
                    System.out.println(str);
                   
                 
                   
                }while(!str.equals("stop"));
    }
}


Cajero automatico en JAVA

    float cant;
    InputStreamReader is;
    is=new InputStreamReader(System.in);
    BufferedReader bf=new BufferedReader(is);
    do{
      System.out.println("Elegir opción:\n");
      System.out.println("1. Crear cuenta vacía");
      System.out.println("2. Crear cuenta saldo "+
  "inicial");
      System.out.println("3. Ingresar dinero");
      System.out.println("4. Sacar dinero");
      System.out.println("5. Ver saldo");
      System.out.println("6. Salir\n");
      op=bf.readLine();
      switch(Integer.parseInt(op)){
        case 1:
            c=new Cuenta();
            break;
        case 2:
            System.out.println("Saldo inicial: ");
            float inicial=
Float.parseFloat(bf.readLine());
            c=new Cuenta(inicial);
            break;
        case 3:
            System.out.println("Introduzca cantidad "+
  " a ingresar: ");
            cant=Integer.parseInt(bf.readLine());
            c.ingresar(cant);
            break;
        case 4:
            System.out.println("Cantidad a extraer: ");
            cant=Integer.parseInt(bf.readLine());
            try{
              c.extraer(cant);
            }
            catch(SaldoInsuficienteException e){
              //si se produce la excepción muestra
   //el mensaje asociado
              System.out.println(e.getMessage());
            }
            break;
        case 5:
            System.out.println("Su saldo actual "+
" es de: "+c.getSaldo());
            break;
      }
    }
    while(!op.equals("6"));
  }
}

Conecta 4 consola C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Desarrollo
{
    class Program
    {


        char[,] tablero = new char[12, 12];

        void inicializar_tablero()
        {
            int i, j;
            for (i = 0; i < 12; i++)
                for (j = 0; j < 12; j++)
                    tablero[i, j] = ' ';
        }



        int jugada_corrrecta(int fila, int col)
        {
            int jugada_correcta;
            jugada_correcta = 1;

            if (fila >= 12 || fila < 0 || col >= 12 || col < 0)

                jugada_correcta = 0;

            if (jugada_correcta == 1)
            {
                if (tablero[fila, col] == '0' || tablero[fila, col] == 'X')
                    jugada_correcta = 0;
            }


            if (jugada_correcta == 1)
            {
                if (fila != 12 -1 && tablero[fila + 1, col] == ' ')
                    jugada_correcta = 0;

            }

            return jugada_correcta;

        }




        int hacer_jugada(int jug)
        {
            int fila, col;
            int i;
            char ficha;
            int resultado_jugada;
            resultado_jugada = 1;
            col = 0;

            if (jug == 0)
            {
                ficha = '0';
                Console.WriteLine("!!!!!! El usuario coloca ficha !!!!.\n");

                do
                {

                    if (resultado_jugada == 0)
                     
                        Console.WriteLine("Jugada Incorrecta.\n");

                    Console.Write("Introduce la columna en la que quieres colocar la ficha: ");
                    //creo que era columa y no ficha
                    col = int.Parse(Console.ReadLine());

                    i = 12 - 1;

                    if (tablero[12 - 1, col] != ' ')
                    {
                        while (i < 12 && (tablero[i, col] == 'X' || tablero[i, col] == '0'))

                            i--;

                    }

                    fila = i;

                    resultado_jugada = jugada_corrrecta(fila, col);

                } while (resultado_jugada == 0);

            }
            else
            {
                ficha = 'X';

                do
                {

                    col = generar_numero();

                    i = 12 - 1;

                    if (tablero[12 - 1, col] != ' ')
                    {
                        while (i < 12 && (tablero[i, col] == 'X' || tablero[i, col] == '0'))
                            i--;
                    }

                    fila = i;

                    resultado_jugada = jugada_corrrecta(fila, col);

                } while (resultado_jugada == 0);
            }

            if (resultado_jugada == 1)

                tablero[fila, col] = ficha;

            return resultado_jugada;

        }




        int generar_numero()
        {
            int num;
            num = 0;
            Random rnd = new Random();

            num = rnd.Next(0, 12);

            return num;

        }


     
       
           void mostrar_tablero()  //pinta
        {
            int i, j;
            int ficha;

            Console.Clear();  // verificar este clear tal vez se un mensaje "Clear"
            Console.WriteLine("\n");


            for (j = 0; j < 8 * 5 / 2; j++)
                Console.WriteLine("  ");

       
            Console.WriteLine("_____________________CONECTA 4________________");
           
            Console.Write("\n F ---------");
         
         
            //Console.Write("\t F -");

            for (j = 0; j < 12 + 1; j++)

                Console.Write("----");
            Console.Write("\n");

            for (i = 0; i < 12; i++)
            {
                Console.Write(" ");
                if (i == 0)
                    Console.Write("I");
                else if (i == 1)
                    Console.Write("A");

                else
                    Console.Write(" ");

                Console.Write(" | ", i);

                for (j = 0; j < 12; j++)
                {
                    Console.Write(" ");
                    Console.Write(tablero[i, j]);
                    Console.Write(" | ");
                }

                Console.Write(" ");
                if (i == 0)
                    Console.Write("\n L");
                else if (i == 1)
                    Console.Write("\n S");

                else
                    Console.Write("\n ");
                Console.Write(" -------");

                for (j = 0; j < 8 + 1; j++)

                    Console.Write("------");

                Console.Write("\n");
            }


            Console.Write("                    ");
            for (j = 0; j < 12; j++)

                Console.Write(" ", j);

            Console.Write("COLUMNAS  12\n");     //verificar aqui tal vez sea el nombre COLUMNAS  y no el numero del valor

            Console.Write("\n");
         
        }
   
       


        int comprobar_fin()
        {
            int i, j;
            int ganador;

            ganador = -1;

            //comprobar si hay 4 en linea horizontal

            for (i = 0; i < 12; i++)
            {
                for (j = 0; j < 12 - 3; j++)
                {
                    if (tablero[i, j] == 'X' && tablero[i, j + 1] == 'X' && tablero[i, j + 2] == 'X' && tablero[i, j + 3] == 'X')

                        ganador = 0;
                    else if (tablero[i, j] == '0' && tablero[i, j + 1] == '0' && tablero[i, j + 2] == '0' && tablero[1, j + 3] == '0')

                        ganador = 1;
                }
            }

            if (ganador == -1)
            {
                //comprovar si hay 4 en linea vertical

                for (i = 0; i < 12 - 3; i++)
                {
                    for (j = 0; j < 12; j++)
                    {
                        if (tablero[i, j] == 'X' && tablero[i + 1, j] == 'X' && tablero[i + 2, j] == 'X' && tablero[i + 3, j] == 'X')

                            ganador = 0;
                        else if (tablero[i, j] == '0' && tablero[i + 1, j] == '0' && tablero[i + 2, j] == '0' && tablero[i + 3, j] == '0')

                            ganador = 1;
                    }
                }
            }

            if (ganador == -1)
            {
                //comprobar si hay cuatro en linea diagonal 1

                for (i = 0; i < 12; i++)
                {
                    for (j = 0; j < 12; j++)
                    {
                        if (i + 3 < 12 && j + 3 < 12)
                        {
                            if (tablero[i, j] == 'X' && tablero[i + 1, j + 1] == 'X' && tablero[i + 2, j + 2] == 'X' && tablero[i + 3, j + 3] == 'X')

                                ganador = 0;
                            else if (tablero[i, j] == '0' && tablero[i + 1, j + 1] == '0' && tablero[i + 2, j + 2] == '0' && tablero[i + 3, j + 3] == '0')
                                ganador = 1;
                        }
                    }
                }
            }


            if (ganador == -1)
            {
                //comprobar si hay cuatro en linea en diagonal 2

                for (i = 0; i < 12; i++)
                {
                    for (j = 0; j < 12; j++)
                    {
                        if (i + 3 < 12 && j - 3 >= 0)
                        {
                            if (tablero[i, j] == 'X' && tablero[i + 1, j - 1] == 'X' && tablero[i + 2, j - 2] == 'X' && tablero[i + 3, j - 3] == 'X')

                                ganador = 0;

                            else if (tablero[i, j] == '0' && tablero[i + 1, j - 1] == '0' && tablero[i + 2, j - 2] == '0' && tablero[i + 3, j - 3] == '0')

                                ganador = 1;
                        }
                    }
                }
            }


            return ganador;
        }

        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.Clear();


            Program Arranque = new Program();

            int jugador;
            int total_jugadas;
            total_jugadas = 0;

            Arranque.inicializar_tablero();

            do
            {

                if (total_jugadas % 2 == 0)

                    jugador = 0;
                else
                    jugador = 1;

                total_jugadas++;

                Arranque.mostrar_tablero();

                if (Arranque.hacer_jugada(jugador) == 0)
                {
                    Console.WriteLine("Jugada Incorrecta.\n\n");

                    //Console.WriteLine("Pause");   // verificar esto
                    Console.ReadLine();

                }
            } while (Arranque.comprobar_fin() == -1);


            Arranque.mostrar_tablero();

            if (Arranque.comprobar_fin() == 1)

                Console.WriteLine("Haz Ganado.\n\n");

            else

                Console.WriteLine("Ganá la computadora!!\n\n");
        }
    }
}
       






















Ejemplo en C# StreamWriter

Otro ejemplo sencillos de streamwritter utilizando arreglos: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int t;
Console.WriteLine("Cuantos datos necesita capturar : ?");
t =Convert.ToInt32(Console.ReadLine());

string[]a=new string [t];

for (int i = 0; i<a.Length; i++)
{
Console.WriteLine("nombre: ");
a[i] =Console.ReadLine();

}
Console.WriteLine();

Console.WriteLine("");

for (int j = 0; j <a.Length; j++)
{
//Console.WriteLine(a[j]);

StreamWriter texto = File.AppendText("agenda.txt");

texto.WriteLine(""+a[j]);
texto.Close();

}

Console.WriteLine("!!!!!!!!!!!registros almacenados correctamente!!!!!!!!!!!!!!!!!!!!");
Console.ReadLine();

}
}
}

domingo, 29 de diciembre de 2013

Lista enlazada Java LinkedList

package listaenlazada;
import java.util.*;


/**
 *
 * @author Josue
 */
public class ListaEnlazada {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        //crear o unicializar una lista enlazada
       
        LinkedList<Integer> l1=new LinkedList<Integer>();
       
       
        l1.add(3);
        l1.add(1);
        l1.add(9);
        l1.add(6);
        l1.add(10);
     
       
       
         //creamos un comparador de orden inverso
       
        Comparator<Integer> r=Collections.reverseOrder();
       
        //ordenar lal ista utilizando el comparador
       
        Collections.sort(l1,r);
       
        System.out.println("Lista en orden inverso decreciente:");
        for(int i:l1)
            System.out.print(i+"-");
       
        System.out.println();
       
        //mezclar lista
       
        Collections.shuffle(l1);
       
        //mostrar la lista aleatoriamente
        System.out.println("Aleatoriamente:");
        for(int i:l1)
            System.out.print(i+"-");
       
        System.out.println();
       
        System.out.println("Minimo:"+Collections.min(l1));
        System.out.println("Maximo: "+Collections.max(l1));
       

       
    }
}

viernes, 25 de octubre de 2013

Convertidor de grados Java




import javax.swing.*;


public class Conversor extends javax.swing.JFrame {
    private Object objJTextField;

 
    public Conversor() {
        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        etGradosC = new javax.swing.JLabel();
        etGradosF = new javax.swing.JLabel();
        ctGradosC = new javax.swing.JTextField();
        ctGradosF = new javax.swing.JTextField();
        btAceptar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Conversion De Temperaturas");

        etGradosC.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        etGradosC.setText("Grados Centigrados");

        etGradosF.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        etGradosF.setText("Grados Fahrenheit");

        ctGradosC.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        ctGradosC.setText("0.00");
        ctGradosC.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ctGradosCKeyTyped(evt);
            }
        });

        ctGradosF.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        ctGradosF.setText("32.00");
        ctGradosF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ctGradosFKeyTyped(evt);
            }
        });

        btAceptar.setMnemonic('A');
        btAceptar.setText("Aceptar");
        btAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAceptarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(etGradosC)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(ctGradosC, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(etGradosF)
                            .addGap(18, 18, 18)
                            .addComponent(ctGradosF, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(24, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(72, 72, 72)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(etGradosC)
                    .addComponent(ctGradosC, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(60, 60, 60)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(etGradosF, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ctGradosF))
                .addGap(28, 28, 28)
                .addComponent(btAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAceptarActionPerformed
       
        try
        {
          double grados;
           
         
          if(objJTextField==ctGradosC)
          {
           grados=Double.parseDouble(ctGradosC.getText())*9.0/5.0+32.0;
           String texto=String.format("%.2f",grados);   //redondear a decimales
           ctGradosF.setText(texto);
          }
         
          if(objJTextField==ctGradosF)
          {
              grados=(Double.parseDouble(ctGradosF.getText())-32.0)*5.0/9.0;
              String texto=String.format("%.2f",grados);
              ctGradosC.setText(texto);
          }
        }
       
        catch(NumberFormatException e)
        {
            ctGradosC.setText(".00");
                   
           ctGradosF.setText("32.00");
         
           
        }
       
       
       
    }//GEN-LAST:event_btAceptarActionPerformed

    private void ctGradosCKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ctGradosCKeyTyped
        // TODO add your handling code here:
        objJTextField=evt.getSource();
       
    }//GEN-LAST:event_ctGradosCKeyTyped

    private void ctGradosFKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ctGradosFKeyTyped
        // TODO add your handling code here:
        objJTextField=evt.getSource();
       
    }//GEN-LAST:event_ctGradosFKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Conversor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Conversor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Conversor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Conversor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Conversor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAceptar;
    private javax.swing.JTextField ctGradosC;
    private javax.swing.JTextField ctGradosF;
    private javax.swing.JLabel etGradosC;
    private javax.swing.JLabel etGradosF;
    // End of variables declaration//GEN-END:variables
}

Calculadora en JAVA





import javax.swing.*;
import java.awt.event.*;
import java.util.HashSet;

/*
 *
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author JOSUE
 */

public class Calculadora extends javax.swing.JFrame {

    private Entrada ultimaEntrada;
    private boolean puntoDecimal;
    private char operador;
    private byte numOperandos;
    private double operando1,operando2;
   
    private enum Entrada{NINGUNA,DIGITO,OPERADOR,CE};
    /**
     * Creates new form Calculadora
     */
    public Calculadora()
    {
   
        initComponents();
        ultimaEntrada=  Entrada.NINGUNA;
        puntoDecimal=false;
        numOperandos=0;
        operando1=0;
        operando2=0;
       
    }
   
   
   
    /**
     * 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbtDigito18 = new javax.swing.JButton();
        jtfPantalla = new javax.swing.JTextField();
        jbtDigito8 = new javax.swing.JButton();
        jbtDigito7 = new javax.swing.JButton();
        jbtDigito9 = new javax.swing.JButton();
        jbtDigito4 = new javax.swing.JButton();
        jbtDigito5 = new javax.swing.JButton();
        jbtDigito6 = new javax.swing.JButton();
        jbtDigito2 = new javax.swing.JButton();
        jbtDigito3 = new javax.swing.JButton();
        jbtDigito1 = new javax.swing.JButton();
        jbtDigito0 = new javax.swing.JButton();
        jbtDigitoPunto = new javax.swing.JButton();
        jbtDividir = new javax.swing.JButton();
        jbtInicial = new javax.swing.JButton();
        jbtMenos = new javax.swing.JButton();
        jbtMas = new javax.swing.JButton();
        jbtBorrarEntrada = new javax.swing.JButton();
        jbtIgual = new javax.swing.JButton();
        jbtPor = new javax.swing.JButton();
        jbtTantoPorCiento = new javax.swing.JButton();

        jbtDigito18.setText("9");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Calculadora");
        setBackground(new java.awt.Color(204, 255, 255));
        setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        jtfPantalla.setEditable(false);
        jtfPantalla.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        jtfPantalla.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jtfPantalla.setText("0.");

        jbtDigito8.setText("8");
        jbtDigito8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito7.setText("7");
        jbtDigito7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito9.setText("9");
        jbtDigito9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito4.setText("4");
        jbtDigito4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito5.setText("5");
        jbtDigito5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito6.setText("6");
        jbtDigito6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito2.setText("2");
        jbtDigito2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito3.setText("3");
        jbtDigito3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito1.setText("1");
        jbtDigito1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigito0.setText("0");
        jbtDigito0.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoActionPerformed(evt);
            }
        });

        jbtDigitoPunto.setText(".");
        jbtDigitoPunto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDigitoPuntoActionPerformed(evt);
            }
        });

        jbtDividir.setText("/");
        jbtDividir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtOperacionActionPerformed(evt);
            }
        });

        jbtInicial.setText("C");
        jbtInicial.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtInicialActionPerformed(evt);
            }
        });

        jbtMenos.setText("-");
        jbtMenos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtOperacionActionPerformed(evt);
            }
        });

        jbtMas.setText("+");
        jbtMas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtOperacionActionPerformed(evt);
            }
        });

        jbtBorrarEntrada.setText("CE");
        jbtBorrarEntrada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtBorrarEntrada(evt);
            }
        });

        jbtIgual.setText("=");
        jbtIgual.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtOperacionActionPerformed(evt);
            }
        });

        jbtPor.setText("X");
        jbtPor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtOperacionActionPerformed(evt);
            }
        });

        jbtTantoPorCiento.setText("%");
        jbtTantoPorCiento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtTantoPorCientoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jbtDigito0, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtDigitoPunto, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jbtDigito7, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jbtDigito8, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jbtDigito4, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jbtDigito5, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jbtDigito1, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jbtDigito2, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jbtDigito6, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jbtDigito9, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jbtDigito3, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(54, 54, 54)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jbtDividir, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtMenos, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jbtPor, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jbtMas, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(0, 0, Short.MAX_VALUE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                                        .addComponent(jbtTantoPorCiento, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(jbtInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(jbtBorrarEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                            .addComponent(jbtIgual, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(jtfPantalla, javax.swing.GroupLayout.PREFERRED_SIZE, 348, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(22, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(jtfPantalla, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jbtDigito7, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jbtDigito8, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jbtDigito9, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jbtBorrarEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jbtInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtDigito6, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtDigito5, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtDigito4, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtMenos, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtDividir, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtDigito3, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtDigito2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtDigito1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jbtDigito0, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtDigitoPunto, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtMas, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtPor, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtTantoPorCiento, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtIgual, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtDigitoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtDigitoActionPerformed
        // TODO add your handling code here:
       
       
     
       
       
         JButton objJBT=(JButton)evt.getSource();
         String textoBoton=objJBT.getText();
       
         if(ultimaEntrada !=Entrada.DIGITO)
         {
             if(textoBoton.compareTo("0")==0)return;
             jtfPantalla.setText("");
             ultimaEntrada=Entrada.DIGITO;
         }
       
  jtfPantalla.setText(jtfPantalla.getText() + textoBoton);
 
       
    }//GEN-LAST:event_jbtDigitoActionPerformed

    private void jbtDigitoPuntoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtDigitoPuntoActionPerformed
        // TODO add your handling code here:
        if(ultimaEntrada !=Entrada.DIGITO)
        {
            jtfPantalla.setText("0.");
            ultimaEntrada=Entrada.DIGITO;
        }
       
        else if(puntoDecimal==false)
       
            jtfPantalla.setText(jtfPantalla.getText()+ ".");
        puntoDecimal=true;
     
    }//GEN-LAST:event_jbtDigitoPuntoActionPerformed

    private void jbtOperacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtOperacionActionPerformed
        // TODO add your handling code here:
       
        JButton objJBT=(JButton)evt.getSource();
        String textoBoton=objJBT.getText();
       
        if((numOperandos == 0) && (textoBoton.compareTo("-")==0))
         ultimaEntrada = Entrada.DIGITO;
       
          if (ultimaEntrada == Entrada.DIGITO)
      numOperandos++;
     
         
               
       
        if(numOperandos==1)
            operando1=Double.parseDouble(jtfPantalla.getText());
        else if(numOperandos==2)
        {
            operando2=Double.parseDouble(jtfPantalla.getText());
           
            switch (operador)
            {
                case '+':
                    operando1 +=operando2;
                    break;
                   
                   
                case '-':
                    operando1 -=operando2;
                    break;
                   
                   
                case 'X':
                   
                    operando1 *= operando2;
                    break;
                   
                   
                case '/':
                    operando1/=operando2;
                    break;
                   
                   
                   
                case '=':
                    operando1=operando2;
                    break;  
            }
           
            jtfPantalla.setText(Double.toString(operando1));
            numOperandos=1;
           
        }
       
        operador=textoBoton.charAt(0);
        ultimaEntrada=Entrada.OPERADOR;
   
    }//GEN-LAST:event_jbtOperacionActionPerformed

    private void jbtTantoPorCientoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtTantoPorCientoActionPerformed
        // TODO add your handling code here:
       
        double resultado;
       
        if(ultimaEntrada==Entrada.DIGITO)
        {
            resultado=operando1*Double.parseDouble(jtfPantalla.getText())/100;
            jtfPantalla.setText(Double.toString(resultado));
           
            jbtIgual.doClick();
           jbtTantoPorCiento.requestFocus();
        }
       
       
    }//GEN-LAST:event_jbtTantoPorCientoActionPerformed

    private void jbtInicialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtInicialActionPerformed
        // TODO add your handling code here:
       
        jtfPantalla.setText("0.");
        ultimaEntrada=Entrada.NINGUNA;
        puntoDecimal=false;
        operador=0;
        numOperandos=0;
        operando1=0;
        operando2=0;
    }//GEN-LAST:event_jbtInicialActionPerformed

    private void jbtBorrarEntrada(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtBorrarEntrada
        // TODO add your handling code here:
        jtfPantalla.setText("0.");
        ultimaEntrada=Entrada.CE;
        puntoDecimal=false;
       
    }//GEN-LAST:event_jbtBorrarEntrada

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Calculadora().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jbtBorrarEntrada;
    private javax.swing.JButton jbtDigito0;
    private javax.swing.JButton jbtDigito1;
    private javax.swing.JButton jbtDigito18;
    private javax.swing.JButton jbtDigito2;
    private javax.swing.JButton jbtDigito3;
    private javax.swing.JButton jbtDigito4;
    private javax.swing.JButton jbtDigito5;
    private javax.swing.JButton jbtDigito6;
    private javax.swing.JButton jbtDigito7;
    private javax.swing.JButton jbtDigito8;
    private javax.swing.JButton jbtDigito9;
    private javax.swing.JButton jbtDigitoPunto;
    private javax.swing.JButton jbtDividir;
    private javax.swing.JButton jbtIgual;
    private javax.swing.JButton jbtInicial;
    private javax.swing.JButton jbtMas;
    private javax.swing.JButton jbtMenos;
    private javax.swing.JButton jbtPor;
    private javax.swing.JButton jbtTantoPorCiento;
    private javax.swing.JTextField jtfPantalla;
    // End of variables declaration//GEN-END:variables
}

viernes, 18 de octubre de 2013

Aprender a programar

La programación de computadoras es una actividad fascinante, el poder hacer una aplicación a la medida y de acuerdo a nuestras necesidades es una actividad interesante y llena de recompensas.

Mucha gente llega a pensar que solamente con aprender la sintaxis de un lenguaje de programación es suficiente para poder hacer programas, pero se equivocan. Aun más importante que la sintaxis del lenguaje es la técnica de resolución del problema y el análisis adecuado.

El tener buenos hábitos de análisis y programación desde el inicio es fundamental para convertirnos en buenos programadores.