domingo, 29 de septiembre de 2013

Probando un poco de Ceylon

Nueva versión: "Virtual Boy": http://ceylon-lang.org/download/

Compilar:
ceylon compile source\programa.ceylon

Ejecutar:
ceylon run default

1. Crear una simple clase:
void run(){
Prueba code=Prueba();
  print(code.getUsuario());

}

shared class Prueba(){
  shared String getUsuario(){
     String usuario="Andrea";
    return "Hola ``usuario``";
  }
}

2. Uso de interface en Ceylon:
shared void run(){
   miObjeto.imprime();
}

interface Servicio{
    shared String  ver{
      return "tratando de conquistar el mundo";
    }
}
//algo parecido a: class MiClase implements Interface  ,en Java
object miObjeto satisfies Servicio{
  shared void imprime(){
     print(ver);
  }
}

Más de Ceylon

Links
https://gist.github.com/HiroNakamura/4731442

domingo, 22 de septiembre de 2013

Programando en Java ... no. 5

"Mientras tanto el programador trata de entender el mundo a través de código, olvidando que puede hacerlo con un simple vistazo"


1. Creando nuestras propias excepciones, creamos una clase llamada "MyNumberException" que extiende de la clase Exception, si el número es mayor a 500 o menor a 0 ocurrirá la excepción

public class Codemonkey{
   
     static void setValor(int x)throws MyNumberException{
         if(x>500 || x<0)
             throw new MyNumberException("debes introducir un valor menor a 500 y mayor a 0");
          // se ejecutará si el número es mayor a 500 o menor a 0
     }
    public static void main(String[] args)throws MyNumberException{
        System.out.println("    c0D3m0Nk3Y    ");
       try{
            setValor(501);
        }catch(MyNumberException me){
           System.err.println("Ha ocurrido un error: "+me.getMessage());//mostramos el mensaje
        }finally{
             System.out.println("finally: esto siempre se ejecutara");
        }
        System.out.println("esto esta fuera del try-catch-finally");
    }  
}

class MyNumberException  extends Exception{
    public  MyNumberException(String message){
         super(message);
    }
}
Para ejecutar es necesario habilitar las "assertions" en java con "-ea":
javac -g Codemokey.java
java -ea Codemonkey

2. En este ejemplo se usa la clase HashSet para insertar un valor de tipo "Persona", si el valor es un duplicado no se podrá insertar.

import java.util.HashSet;
import java.util.Objects;


public class Codemonkey {
    public static void main(String[] args){
     HashSet persons=new HashSet();
     persons.add(new Persona("Laura",31));
     persons.add(new Persona("Hortencia",21));
     persons.add(new Persona("Laura",31));//duplicado
     persons.ass(new Persona("Hortencia",39)); //este valor si se agrega
   
     for(Object p: persons){
         Persona per=(Persona)p;
      System.out.println(per.getNombre()+"  - "+per.getEdad());
     }
   
     System.out.println(persons.toString());
   
    }
}

//aquí creamos la clase Persona
class Persona{
    private String nombre;
    private int edad;

    public Persona(String nombre, int edad) {
        this.nombre = nombre;
        this.edad = edad;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public void setEdad(int edad) {
        this.edad = edad;
    }

    public String getNombre() {
        return nombre;
    }

    public int getEdad() {
        return edad;
    }
   
    @Override
    public String toString(){
        return "nombre: "+nombre+"  edad: " +edad;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 79 * hash + this.edad;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Persona other = (Persona) obj;
        if (!Objects.equals(this.nombre, other.nombre)) {
            return false;
        }
        if (this.edad != other.edad) {
            return false;
        }
        return true;
    }
}


3. Ejecutando un hilo en java swing
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;



public class Codemonkey{
    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            @Override
            public void run() {
                new Ventana();
            }
        });
    }
}

class Ventana extends JFrame{
    private JPanel panel;
    private JButton btnSalir,btnActiva;

    Ventana(){
        setTitle("Iniciando hilos");
        setSize(450,300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(getGUI());
    }

    public JPanel getGUI(){
        panel=new JPanel();
        panel.setVisible(true);
        panel.setSize(700,400);
        panel.setBackground(Color.black);
        panel.add(new JLabel("<html><h1><font color='white'>Ejecutando un hilo</font></h1></html>"));
        panel.add(getBtnActiva());
        panel.add(getBtnSalir());
        return panel;
    }


    public JButton getBtnActiva(){
        btnActiva=new JButton("<html><font color='white'>Iniciar hilo</font></html>",new ImageIcon("mono.jpg"));
        btnActiva.setToolTipText("quitar ventana ...");
        btnActiva.setBackground(Color.blue);
        btnActiva.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e){
                   
                    new Thread(new Runnable(){
                        public void run(){
                            int cont=0;
                            System.out.println("Inicia hilo");
                            while(cont<4){
                            try{
                                Thread.sleep(1000);
                               System.out.println("Hola no. "+(cont+1));
                            cont++;
                        }catch(InterruptedException ex){
                            System.err.println(ex.toString());
                        }
                        System.out.println("Termina hilo");

                           }
                        }
                    }).start();


           }
       });

        return btnActiva;
    }

    public JButton getBtnSalir(){
        btnSalir=new JButton("<html><font color='white'>Salir</font></html>",new ImageIcon("mono.jpg"));
        btnSalir.setToolTipText("quitar ventana ...");
        btnSalir.setBackground(Color.red);
        btnSalir.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e){
                    System.exit(0);
           }
       });

        return btnSalir;
    }
}




sábado, 14 de septiembre de 2013

Programando en C# ... no.1

El lenguaje C# es una respuesta al popular lenguaje de programación Java por parte de Microsoft, es bastante similar (algunos dicen es una "copia exacta" a Java).

Hola mundo en Java
System.out.println("¡Hola, mundo en Java!");

Hola mundo en C#
Console.WriteLine("¡Hola, mundo en C#!");

Los archivos deben tener la extensión *.cs, puedes usar MonoDevelop, SharpDevelop o Visual Studio para programar en C#.

using System;

namespace Codemonkey.cs
{
class Program
{
public static void Main(string[] args)
{
                   // AQUÍ COLOCAS EL CÓDIGO
}
}
}

Si ya haz usado Java la sintaxis te parecerá muy familiar.

1. Creando una clase llamada "Persona"
using System;

namespace Codemonkey.cs
{
//aquí inicia la clase Persona
class Persona{
string nombre;
int edad;

public Persona(){}

public void SetNombre(string n){
nombre=n;
}

public void SetEdad(int d){
edad=d;
}

public int GetEdad(){
return edad;
}

public string GetNombre(){
return nombre;
}

}//aquí termina la clase Persona
class Program
{
public static void Main(string[] args)
{

Persona persona=new Persona();
persona.SetNombre("Antonio");
persona.SetEdad(28);

Console.WriteLine("nombre: "+persona.GetNombre()+" , edad: "+persona.GetEdad());
Console.Write("Presiona una tecla para continuar . . . ");
                Console.ReadKey(true);
       }
    }
}

El código resulta muy familiar y fácil de entender a los que ya han usado Java.

2. Introducir datos, los tipos de datos son prácticamente iguales a Java.
using System;

namespace Codemonkey.cs
{

class Program
{
public static void Main(string[] args)
{

 float flotante;
 int entero;
 double real;
 string cadena;
 char car;

 Console.WriteLine("Introduce un numero flotante: ");
 flotante=float.Parse(Console.ReadLine());
 Console.WriteLine("Introduce un numero entero: ");
 entero=int.Parse(Console.ReadLine());
 Console.WriteLine("Introduce un numero real: ");
 real=double.Parse(Console.ReadLine());
 Console.WriteLine("Introduce una cadena: ");
 cadena=Console.ReadLine();
 Console.WriteLine("Introduce un caracter: ");
 car= char.Parse(Console.ReadLine());

 Console.WriteLine("entero: "+entero);
 Console.WriteLine("flotante: "+flotante);
 Console.WriteLine("real: "+real);
 Console.WriteLine("cadena: "+cadena);
 Console.WriteLine("caracter: "+car);
 Console.Write("Presiona una tecla para continuar . . . ");
  Console.ReadKey(true);
       }
    }
}

3. Usando constantes
using System;

namespace Codemonkey.cs
{
class Prueba{
                //se define la constante "TAM"
public const int TAM=10;
               //en Java sería
              //public static final int TAM=10;
}

class Program
{
public static void Main(string[] args)
{
int tam=Prueba.TAM;

for(int i=0;i<tam;i++){
Console.WriteLine("valor de i: "+i);
}

Console.Write("Presiona una tecla para continuar . . . ");
               Console.ReadKey(true);

   }
}
}

4. Comparar dos cadenas
using System;

namespace Codemonkey.cs
{


class Program
{
public static void Main(string[] args)
{
string cad1="Yo programo en Java";
           string cad2="Yo prefiero usar C#";
         
          //en Java podríamos usar el método cad1.equals(cad2);
           if(cad1==cad2){
            Console.WriteLine("son idénticas las cadenas");
           }else{
            Console.WriteLine("NO son idénticas las cadenas");
           }

Console.Write("Presiona una tecla para continuar . . . ");
       Console.ReadKey(true);

   }
}
}  


Links
http://eqcode.com/wiki/CSharp
http://msdn.microsoft.com/es-es/library/67ef8sbd(v=vs.90).aspx

domingo, 8 de septiembre de 2013

Un vistazo a ... C#


Instalar SharpDevelop
Comenzamos descargando e instalando este IDE http://www.icsharpcode.net/opensource/sd/ para programar en C#. Es una herramienta Open Source para crear aplicaciones .Net. 

Una vez instalado, creamos un proyecto File -> New -> Solution, elegimos "Console Application".
Le damos un nombre al proyecto.


1. Entrada y salida
using System;

namespace Codemonkey.cs
{
class Program
{
public static void Main(string[] args)
{

      String nombre;
      Console.WriteLine("Introduzca tu nombre");
      nombre=Console.ReadLine();
      Console.WriteLine("Hola " + nombre);
      Console.Write("Presiona una tecla para continuar . . . ");
      Console.ReadKey(true);

}
}
}

2. Calcular el valor futuro dada una cantidad invertida
using System;

namespace Codemonkey.cs
{
class Program
{
public static void Main(string[] args)
{

      double valor=4500.0;
double tasa=7.0/12.0;
int plazo=4;
double valorFuturo;
for(int i=0;i<plazo;i++){
valorFuturo=valor*Math.Pow(1+tasa,i);
Console.WriteLine("valor futuro generado: "+valorFuturo+" para el periodo: "+(i+1));
}
Console.Write("Presiona una tecla para continuar . . . ");
Console.ReadKey(true);

}
}
}

Links
http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java

lunes, 2 de septiembre de 2013

Programando en C++ ... no.2

1. Clases, crear una clase llamada "Fecha" y mostrar sus propiedades.
#include "iostream.h"
#include "stdio.h"
#include "time.h"
#include "stdlib.h"

class Fecha{
      private:
              int dia;
              int mes;
              int anyo;
   
      public:
             Fecha();
             virtual ~Fecha();
           
             Fecha(int dia,int mes, int anyo){
                       this->dia=dia;
                       this->mes=mes;
                       this->anyo=anyo;
             }
           
             void setDia(int dia){this->dia=dia;}
             void setMes(int mes){this->mes=mes;}
             void setAnyo(int anyo){this->anyo=anyo;}
           
             int getDia(){return this->dia;}
             int getMes(){return this->mes;}
             int getAnyo(){return this->anyo;}
             
};

Fecha::Fecha(){
             cout<<"Se ha creado objeto Fecha"<<endl;
}

Fecha::~Fecha(){cout<<"Se ha destruido objeto Fecha"<<endl;}


int main(){
    Fecha fecha(18,12,1981);
    cout<<"dia: "<<fecha.getDia()<<"  mes: "<<fecha.getMes()<<"  anyo: "<<fecha.getAnyo()<<endl;
    system("PAUSE");
    return 0;
}

Links:
Libro C/C++/Java