Friday, December 13, 2013

Sqlite

package ad2_practica2_ejercicio1;

import java.sql.*;

public class Database {

 protected Connection connection;
 protected Statement query;
 
 public Database() throws ClassNotFoundException, SQLException{
  Class.forName("org.sqlite.JDBC");
  connection = DriverManager.getConnection("jdbc:sqlite:db.sqlite");
  query = null;
 }
 
}


package ad2_practica2_ejercicio1;

import java.util.ArrayList;
import java.sql.*;

public class DBLibro extends Database {

 
 public DBLibro() throws ClassNotFoundException, SQLException
 {
  super();
 }
 

 public void Insertar(Libro l) throws Exception
 {
  try
  {
   query = connection.createStatement();
   
   String sql = "INSERT INTO LIBRO (ISBN,TITULO,AUTOR,NUMEJEMPLARES,ANYOPUBLICACION,EDITORIAL,NUMPAG) " +
     "VALUES (" + l.getIsbn() + ", '" + l.getTitulo() + "','"+ l.getAutor()+ "',"+ l.getNumejemplares() + ","+
     l.getAnyopublicacion()+",'" + l.getEditorial() + "'," + l.getNumpag() + ");";
   
   query.executeUpdate(sql);
   
   query.close();
   connection.close();
  }
  catch(Exception e)
  {
   //System.out.println("Error,\n" + e.getMessage());
   throw new Exception("Error, intentando registrar un libro.");
  }
 }

 public Libro LeerLibro(int isbn) throws Exception
 {
  try
  {
   query = connection.createStatement();
   ResultSet rs = query.executeQuery("SELECT * FROM LIBRO WHERE ISBN=" + isbn + ";");

   Libro l = null;
   if ( rs.next() ) {

    l = new Libro();

    l.setIsbn(rs.getInt("isbn"));
    l.setTitulo(rs.getString("titulo"));
    l.setAutor(rs.getString("autor"));
    l.setNumejemplares(rs.getInt("numejemplares"));
    l.setAnyopublicacion(rs.getInt("anyopublicacion"));
    l.setEditorial(rs.getString("editorial"));
    l.setNumpag(rs.getInt("numpag"));
   }

   rs.close();
   query.close();
   connection.close();

   return l;
  }
  catch(Exception e)
  {
   throw new Exception("Error, intentando lee el libro.");
  }
 }

 public ArrayList Leer() throws Exception
 {
  ArrayList libros = new ArrayList();

  try
  {
   query = connection.createStatement();
   ResultSet rs = query.executeQuery("SELECT * FROM LIBRO;");

   Libro l = null;
   while ( rs.next() ) {

    l = new Libro();

    l.setIsbn(rs.getInt("isbn"));
    l.setTitulo(rs.getString("titulo"));
    l.setAutor(rs.getString("autor"));
    l.setNumejemplares(rs.getInt("numejemplares"));
    l.setAnyopublicacion(rs.getInt("anyopublicacion"));
    l.setEditorial(rs.getString("editorial"));
    l.setNumpag(rs.getInt("numpag"));
    
    libros.add(l);
   }

   rs.close();
   query.close();
   connection.close();

   return libros;
  }
  catch(Exception e)
  {
   throw new Exception("Error, intentando leer los libros.");
  }
 }


 public void Eliminar(int isbn) throws Exception
 {
  try {
   query = connection.createStatement();
   String sql = "DELETE from LIBRO where ISBN="+isbn+";";
   query.executeUpdate(sql);
 
   query.close();
   connection.close();
  } 
  catch ( Exception e ) 
  {
   throw new Exception("Error, intentando eliminar el libro.");
  }
 }
}

XML con HTML+XSL

import javax.xml.transform.*;
import java.io.*;

public class XSL {

 
 public boolean toHTML(){
  
  try 
  {
      TransformerFactory tFactory = TransformerFactory.newInstance();

      Transformer transformer =
        tFactory.newTransformer
           (new javax.xml.transform.stream.StreamSource
              ("style.xsl"));

      transformer.transform
        (new javax.xml.transform.stream.StreamSource
              ("biblioteca.xml"),
         new javax.xml.transform.stream.StreamResult
              ( new FileOutputStream("biblioteca_municipal.html")));
      
      
      return true;
  }
  catch (Exception e) {
      return false;
  }
  
  
 }
 
}

XSTREAM

 /*
     * Actualiza todo el listado de libros en un fichero XML "biblioteca.xml" mediante XSTREAM.
     * */
	private static void ActualizarInformacionXSTREAM()
	{
		
		ArrayList biblioteca = LeerBiblioteca();
		
		if (biblioteca.size() == 0)
		{
			System.out.println("\nNo existe ningún libro.\nInserte algún libro antes actualizar la información.\n");	
		}
		else
		{
			try
			{
				XStream xstream = new XStream();
				
				xstream.alias("libro", Libro.class);
				xstream.aliasAttribute(Libro.class, "isbn", "isbn");
				
				xstream.toXML(biblioteca, new FileWriter(new File("biblioteca.xml")));
				
				System.out.println("\nInformación actualizada con éxito.\nSe a creado el archivo biblioteca.xml con todos los libros disponibles.\n");
			}
			catch (Exception ex) 
			{ 
				System.out.println("\nError intentando actualizar la información de la biblioteca.\n.");	
			} 
		}
	}

XML DOM y SAX

// Autor: Juan Antonio Ripoll
// Fecha: 09/10/13

/*
 * Objetivo
 * 
 * REALIZA UN PROGRAMA EN JAVA (UTILIZANDO DOM) QUE CREE UN FICHERO XML 
   DONDE SE ALMACENE LA INFORMACIÓN DE LOS LIBROS DE UNA BIBLIOTECA. 
   (TITULO, AUTOR, ISBN,AÑO PUBLICACIÓN, EDITORIAL, NÚMERO DE PÁGINAS). 
	
   OPCIÓN 1.- INSERTAR LIBRO. 
   OPCIÓN 2.- ACTULIZAR INFORMACIÓN (AQUI GENERA EL XML). 
   OPCIÓN 3.- VISUALIZAR LIBROS MEDIANTE DOM. 
   OPCIÓN 4.- VISUALIZAR LIBROS MEDIANTE SAX. 
   OPCIÓN 5.- SALIR 
   
   AYUDA.- PODEÍS UTILIZAR UN FICHERO PARA GUARDAR LA INFORMACIÓN AL 
   INSERTAR LIBROS (DE CARÁCTERES, ALEATORIO O DE OBJETOS COMO OS RESULTE 
   MAS FÁCIL). Y MEDIANTE DOM LEER ESA INFORMACIÓN Y VOLCARLA EN UN XML QUE 
   SERÍA LA OPCIÓN 2. OPCIONES 3 Y 4 RECORRER EL XML VISUALIZANDOLO. 
 * */

package ad_practica2_ejercicio2;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.w3c.dom.Node;

public class Main 
{
	private static final String LISTADO_LIBROS = "biblioteca.dat";
	private static final String LISTADO_LIBROS_XML = "biblioteca.xml";
	
	public static void main(String[] args) throws NumberFormatException, IOException 
	{
		boolean exit = false;

		do
		{
			DibujarMenu();
			
			switch(getOpcion())
			{
				case 1: 
					InsertarLibros(); 
					break;
				case 2:  
					ActualizarInformacion();
					break;
				case 3: 
					VisualizarDOM();
					break;
				case 4:
					VisualizarSAX();
					break;
				case 5:
					exit = true; 
					break;
			}
		}
		while(!exit);

		System.out.println("Bye!");	
	}
	
	
	/*
	 * Dibuja el menú de opciones de usuario en pantalla
	 * */
	private static void DibujarMenu()
	{
		System.out.println("1.- INSERTAR LIBRO");
		System.out.println("2.- ACTUALIZAR INFORMACIÓN");
		System.out.println("3.- VISUALIZAR LIBROS MEDIANTE DOM.");
		System.out.println("4.- VISUALIZAR LIBROS MEDIANTE SAX.");
		System.out.println("5.- SALIR.");
		
		System.out.println();
	}
	
	
	/*
	 * Optiene la opción que introduce el usuario.
	 * */
	private static int getOpcion() throws NumberFormatException, IOException
	{
		System.out.print("Introduzca una opción: ");	
		
		try
		{
			BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
			return Integer.parseInt(in.readLine());
		}
		catch(Exception e)
		{
			System.out.println("Opción no reconocida por el sistema. Opciones validas [1-5].");
			System.out.println();
			
			return 0;
		}
	}

	
	/*
	 * Guarda un libro en el registro
	 * */
	private static void InsertarLibros()
	{
		if (ExisteFichero(LISTADO_LIBROS)) 
			ActualizaBiblioteca();			
		else 
			CrearBiblioteca();
	}
	
	
	/*
	 * Comprueba si existe un fichero en disco
	 * */
	private static boolean ExisteFichero(String f)
	{
    	try
    	{
    		File fichero = new File(f);
	    	
	    	if (fichero.exists())
	    		return true;
	    	
	    	return false;	
    	}
    	catch (Exception e)
    	{
    		return false;
    	}
    }
	
	
	/*
	 * Crea la biblioteca de libros y inserta el primer libro con cabezera. 
	 * */
	private static void CrearBiblioteca()
	{
		try
		{
			Libro libro = getLibro();
	        	
			if (libro != null)
			{
				ObjectOutputStream o = new ObjectOutputStream(
						new FileOutputStream(LISTADO_LIBROS));
	            
				o.writeObject(libro);
	            
				o.close();
				
				System.out.println("\nLibro insertado correctamente en la biblioteca.\n");
			}
	     } 
	     catch (Exception e)
	     {
	    	 System.out.println("Error, intentado crear la biblioteca.");
	     }
	}
	    
	    
	/*
	 * Actualiza la biblioteca de libros, obtiene un nuevo libro y lo incluye sin cabezera.	 
	 * */
	private static void ActualizaBiblioteca()
	{
		try
	    {
			Libro libro = getLibro();
			
			if (libro != null)
			{
			
				MiObjectOutputStream o = new MiObjectOutputStream(
						new FileOutputStream(LISTADO_LIBROS,true));
	         
				o.writeUnshared(libro);
	          
				o.close();
				
				System.out.println("\nLibro insertado correctamente en la biblioteca.\n");
			}
	    } 
	    catch (Exception e)
	    {
	    	System.out.println("Error, intentado añadir un nuevo libro a la biblioteca.");
	    }
	}
	
	
	/*
	 * Lee todo el listado y lo almacena en una lista de libros.
	 * */
	private static ArrayList LeerBiblioteca() 
	{
		ArrayList biblioteca = new ArrayList();
	    	
	    try
	    {
	    	ObjectInputStream o = new ObjectInputStream(
	    			new FileInputStream(LISTADO_LIBROS));
	               
	        Libro libro = (Libro)o.readObject();
	            
	        while (libro!=null)
	        {
	        	biblioteca.add(libro);
	        	
	        	libro = (Libro)o.readObject();
	        }
	            
	        o.close();
	            
	        return biblioteca;
	    }
	    catch (EOFException ex1)
	    {
	    	return biblioteca;
	    }
	    catch (Exception ex2)
	    {
	        return biblioteca;
	    }
	}
	
	
	/*
	 * Obtiene el libro que introduce el usuario. 
	 * */
	private static Libro getLibro()
	{
		try
		{
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(System.in));
			
			Libro libro = new Libro();
			
			System.out.print("Título: ");
			libro.setTitulo(reader.readLine());
	
			System.out.print("Autor: ");
			libro.setAutor(reader.readLine());
			
			System.out.print("ISBN: ");
			libro.setIsbn(reader.readLine());
	
			System.out.print("Año de publicación: ");
			libro.setAnyo_publicacion(Integer.parseInt(reader.readLine()));
			
			System.out.print("Editorial: ");
			libro.setEditorial(reader.readLine());
			
			System.out.print("Número de páginas: ");
			libro.setNumero_paginas(Integer.parseInt(reader.readLine()));

			return libro;
		}
		catch (Exception e){
			System.out.println("\nError en la recogida de datos del libro.\nEl año de publicación y el número de páginas deben de ser números.\n");
			return null;
		}
	}
	
	
	
	/*
	 * Actualiza todo el listado de libros en un fichero XML "biblioteca.xml" mediante DOM.
	 * */
	private static void ActualizarInformacion()
	{
		
		ArrayList biblioteca = LeerBiblioteca();
		
		if (biblioteca.size() == 0)
		{
			System.out.println("\nNo existe ningún libro.\nInserte algún libro antes actualizar la información.\n");	
		}
		else
		{
			try
			{
				DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = df.newDocumentBuilder();
				Document doc = db.newDocument();		 
				 
				Element nodo_biblioteca = doc.createElement("biblioteca");
				doc.appendChild(nodo_biblioteca);
			 	
				
				for (Libro libro : biblioteca) 
				{
					Element nodo_libro = doc.createElement("libro"); 
					nodo_biblioteca.appendChild(nodo_libro);
						 
					Attr attr = doc.createAttribute("isbn");
					attr.setValue(libro.getIsbn());
					nodo_libro.setAttributeNode(attr);
					
					CrearElemento("titulo", libro.getTitulo(), nodo_libro, doc);
					CrearElemento("autor", libro.getAutor(), nodo_libro, doc);
					CrearElemento("año_publicacion", Integer.toString(libro.getAnyo_publicacion()), nodo_libro, doc);
					CrearElemento("editorial", libro.getEditorial(), nodo_libro, doc);
					CrearElemento("numero_paginas", Integer.toString(libro.getNumero_paginas()), nodo_libro, doc);
				}
					
				TransformerFactory transformerFactory = TransformerFactory.newInstance();
				Transformer transformer = transformerFactory.newTransformer();
				DOMSource source = new DOMSource(doc);
				StreamResult result = new StreamResult(new File("biblioteca.xml"));
			 
				transformer.transform(source, result);
				
				System.out.println("\nInformación actualizada con éxito.\nSe a creado el archivo biblioteca.xml con todos los libros disponibles.\n");
			}
			catch (ParserConfigurationException pce) 
			{ 
				pce.printStackTrace(); 
			} 
			catch (TransformerException tfe) 
			{ 
				tfe.printStackTrace(); 
			}
		}
	}
	

    private static void CrearElemento(String dato, String valor, Element raiz, Document document)
    {
        Element elem=document.createElement(dato);
        Text text = document.createTextNode(valor);
        raiz.appendChild(elem);
        elem.appendChild(text);
    }

	

    /*
     * Visualiza el fichero xml mediante DOM.
     * */
    private static void VisualizarDOM()
    {
    	if (!ExisteFichero(LISTADO_LIBROS_XML))
    	{
    		System.out.println("\nEl fichero XML no existe.\nActualize la información de los libros antes de visualizarlos.\n");
    	}
    	else
    	{
	    	try 
	    	{	 
	    		File fXmlFile = new File("biblioteca.xml");
	    		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	    		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	    		Document doc = dBuilder.parse(fXmlFile);
	    	 
	    		
	    		doc.getDocumentElement().normalize();
	    	  
	    		NodeList nList = doc.getElementsByTagName("libro");
	    	 
	    		
	    		System.out.println("\n---------------------------------");
	    		System.out.println("Lectura de libros mediante DOM.");
	    		System.out.println("---------------------------------\n");
	    		
	    		for (int i=0; i' tags  
				public void characters(char ch[], int start, int length)  throws SAXException 
				{  	
					if (titulo.equals("open")) 
						System.out.println("Título: " + new String(ch, start, length));  
					
					if (autor.equals("open")) 
						System.out.println("Autor: " + new String(ch, start, length));  
					
					if (año_publicacion.equals("open")) 
						System.out.println("Año de publicación: " + new String(ch, start, length));  
					
					if (editorial.equals("open")) 
						System.out.println("Editorial: " + new String(ch, start, length));  
				
					if (numero_paginas.equals("open")) 
						System.out.println("Número de páginas: " + new String(ch, start, length) + "\n");  
				}  
  
				// calls by the parser whenever '>' end tag is found in xml   
				// makes tags flag to 'close'  
				public void endElement(String uri, String localName, String qName) throws SAXException 
				{  
					if (qName.equalsIgnoreCase("TITULO")) 
						titulo = "close";  
					
					if (qName.equalsIgnoreCase("AUTOR")) 
						autor = "close";  
     
					if (qName.equalsIgnoreCase("AÑO_PUBLICACION")) 
						año_publicacion = "close";  
     
					if (qName.equalsIgnoreCase("EDITORIAL")) 
						editorial = "close";  
					
					if (qName.equalsIgnoreCase("NUMERO_PAGINAS")) 
						numero_paginas = "close";  
				}  
			};  
     
			saxParser.parse("biblioteca.xml", defaultHandler);  
		} 
		catch (Exception e) 
		{  
			e.printStackTrace();  
		}  
	}  
}  

package ad_practica2_ejercicio2;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class MiObjectOutputStream extends ObjectOutputStream
{
    /** Constructor que recibe OutputStream */
    public MiObjectOutputStream(OutputStream out) throws IOException
    {
        super(out);
    }

    /** Constructor sin parámetros */
    protected MiObjectOutputStream() throws IOException, SecurityException
    {
        super();
    }

    /** Redefinición del método de escribir la cabecera para que no haga nada. */
    protected void writeStreamHeader() throws IOException
    {
    	
    }
}

package ad_practica2_ejercicio2;

import java.io.Serializable;

public class Libro implements Serializable 
{	
	private static final long serialVersionUID = 1L;
	
	private String titulo;
	private String autor;
	private String isbn;
	private int anyo_publicacion;
	private String editorial;
	private int numero_paginas;
	
	public Libro (String titulo, String autor, String isbn, int anyo_publicacion, String editorial, int numero_paginas)
	{
		this.setTitulo(titulo);
		this.setAutor(autor);
		this.setIsbn(isbn);
		this.setAnyo_publicacion(anyo_publicacion);
		this.setEditorial(editorial);
		this.setNumero_paginas(numero_paginas);
	}
	
	public Libro ()
	{	
		this.setTitulo(null);
		this.setAutor(null);
		this.setIsbn(null);
		this.setAnyo_publicacion(0);
		this.setEditorial(null);
		this.setNumero_paginas(0);
	}

	public String getTitulo() {
		return titulo;
	}

	public void setTitulo(String titulo) {
		this.titulo = titulo;
	}

	public String getAutor() {
		return autor;
	}

	public void setAutor(String autor) {
		this.autor = autor;
	}

	public String getIsbn() {
		return isbn;
	}

	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

	public int getAnyo_publicacion() {
		return anyo_publicacion;
	}

	public void setAnyo_publicacion(int anyo_publicacion) {
		this.anyo_publicacion = anyo_publicacion;
	}

	public String getEditorial() {
		return editorial;
	}

	public void setEditorial(String editorial) {
		this.editorial = editorial;
	}

	public int getNumero_paginas() {
		return numero_paginas;
	}

	public void setNumero_paginas(int numero_paginas) {
		this.numero_paginas = numero_paginas;
	}	
}

Objetos

// Autor: Juan Antonio Ripoll
// Fecha: 09/10/13


/* Objetivo
 * 
 * REALIZA UN PROGRAMA QUE PIDA POR PANTALLA DE UN VEHICULO; LA MARCA, EL 
   MODELO DEL COCHE, LA MATRICULA, LA POTENCIA Y EL COLOR, LOS GUARDE EN UN 
   OBJETO VEHICULO Y LOS ESCRIBA EN UN FICHERO. SI CERRAMOS EL PROGRAMA Y 
   VOLVEMOS A ABRIRLO SE AÑADIRÁN OBJETOS AL FINAL DEL FICHERO.EN EL MISMO 
   PROGRAMA INCORPORA UNA OPCIÓN QUE PERMITA VISUALIZAR POR PANTALLA 
   TODOS LOS COCHES DEL FICHERO. 
   
   OPCIÓN 1.- INSERTAR VEHICULO. 
   OPCIÓN 2.- VISUALIZAR VEHICULOS. 
   OPCIÓN 3.- SALIR. 
 * */

package ad_practica2_ejercicio1;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Main 
{
	private static final String LISTADO_VEHICULOS = "vehiculos.dat";
	
	
	/*
	 * Cuerpo del programa.
	 * */
	public static void main(String[] args) throws NumberFormatException, IOException 
	{
		boolean exit = false;

		do
		{
			DibujarMenu();
			
			switch(getOpcion())
			{
				case 1: 
					InsertarVehiculos(); 
					break;
				case 2: 
					VisualizarVehiculos(); 
					break;
				case 3: 
					exit = true; 
					break;
			}
		}
		while(!exit);

		System.out.println("Bye!");
	}
	
	
	/*
	 * Muestra el menu de opciones de usuario en pantalla.
	 * */
	private static void DibujarMenu()
	{
		System.out.println("1.- INSERTAR VEHICULO");
		System.out.println("2.- VISUALIZAR VEHICULOS");
		System.out.println("3.- SALIR.");
		
		System.out.println();
	}
	
	
	/*
	 * Obtiene la opción seleccionada por el usuario.
	 * */
	public static int getOpcion() throws NumberFormatException, IOException
	{
		System.out.print("Introduzca una opción: ");	
		
		try
		{
			BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
			return Integer.parseInt(in.readLine());
		}
		catch(Exception e)
		{
			System.out.println("\nOpción no reconocida por el sistema. Opciones validas [1-3].\n");
			return 0;
		}
	}
	
	
	/*
	 * Actualiza un nuevo vehículo al listado. Si el listado no existe, 
	 * lo crea y introduce el vehículo
	 * */
	private static void InsertarVehiculos()
	{
		if (ExisteListado()) 
			ActualizaListado();			
		else 
			CrearListado();

		System.out.println("\nVehículo insertado correctamente en el listado.\n");
	}
	
	
	/*
	 * Muestra un listado de todos los vehículos disponibles en pantalla.
	 * */
	private static void VisualizarVehiculos()
	{
		if (ExisteListado())
		{
			ArrayList vehiculos = LeerListado();

			System.out.println("\nLISTADO DE VEHÍCULOS\n");

			for (int i=0;i LeerListado() 
	{
		ArrayList vehiculos = new ArrayList();
	    	
	    try
	    {
	    	ObjectInputStream o = new ObjectInputStream(
	    			new FileInputStream(LISTADO_VEHICULOS));
	               
	        Vehiculo vehiculo = (Vehiculo)o.readObject();
	            
	        while (vehiculo!=null)
	        {
	        	vehiculos.add(vehiculo);
	        	
	        	vehiculo = (Vehiculo)o.readObject();
	        }
	            
	        o.close();
	            
	        return vehiculos;
	    }
	    catch (EOFException ex1)
	    {
	    	return vehiculos;
	    }
	    catch (Exception ex2)
	    {
	    	System.out.println ("Error intentanto leer listado de vehículos.");    
	        return null;
	    }
	}

	
	/*
	 * Obtiene el vehículo que introduce el usuario. 
	 * */
	private static Vehiculo getVehiculo()
	{
		try
		{
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(System.in));
			
			Vehiculo vehiculo = new Vehiculo();
			
			System.out.print("Marca: ");
			vehiculo.setMarca(reader.readLine());
	
			System.out.print("Modelo: ");
			vehiculo.setModelo(reader.readLine());
			
			System.out.print("Matrícula: ");
			vehiculo.setMatricula(reader.readLine());
	
			System.out.print("Potencia: ");
			vehiculo.setPotencia(reader.readLine());
			
			System.out.print("Color: ");
			vehiculo.setColor(reader.readLine());
			
			return vehiculo;
		}
		catch (Exception e){
			System.out.println("Error en la recogida de datos del vehículo.");
			System.out.println();
			
			return null;
		}
	}
	
	
	/*
	 * Muestra todos los datos de un vehículo en pantalla
	 * */
	public static void Mostrar(Vehiculo v)
	{
		System.out.println("Marca: " + v.getMarca());
		System.out.println("Modelo: " + v.getModelo());
		System.out.println("Matrícula: " + v.getMatricula());
		System.out.println("Potencía: " + v.getPotencia());
		System.out.println("Color: " + v.getColor());
		
		System.out.println();
	}
}


package ad_practica2_ejercicio1;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class MiObjectOutputStream extends ObjectOutputStream
{
    /** Constructor que recibe OutputStream */
    public MiObjectOutputStream(OutputStream out) throws IOException
    {
        super(out);
    }

    /** Constructor sin parámetros */
    protected MiObjectOutputStream() throws IOException, SecurityException
    {
        super();
    }

    /** Redefinición del método de escribir la cabecera para que no haga nada. */
    protected void writeStreamHeader() throws IOException
    {
    	
    }
}


package ad_practica2_ejercicio1;
import java.io.Serializable;


public class Vehiculo implements Serializable 
{	
	private static final long serialVersionUID = 1L;
	
	private String marca;
	private String modelo;
	private String matricula;
	private String potencia;
	private String color;
	
	
	public Vehiculo (String marca, String modelo, String matricula, String potencia, String color)
	{
		
		this.marca = marca;
		this.modelo = modelo;
		this.matricula = matricula;
		this.potencia = potencia;
		this.color = color;
		
	}
	
	public Vehiculo ()
	{
		
		this.marca = null;
		this.modelo = null;
		this.matricula = null;
		this.potencia = null;
		this.color = null;
		
	}
	

	public String getMatricula() {
		return matricula;
	}

	public void setMatricula(String matricula) {
		this.matricula = matricula;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
	
	public String getModelo() {
		return modelo;
	}

	public void setModelo(String modelo) {
		this.modelo = modelo;
	}

	public String getPotencia() {
		return potencia;
	}

	public void setPotencia(String potencia) {
		this.potencia = potencia;
	}

	public String getMarca() {
		return marca;
	}

	public void setMarca(String marca) {
		this.marca = marca;
	}	
}

Thursday, December 12, 2013

Ejercicio 4

// Autor: Juan Antonio Ripoll
// Fecha: 03/10/13

// Descripción

/*
 *  REALIZA UN PROGRAMA QUE CONTENGA UN MENU QUE APAREZCA EN PANTALLA Y 
   
    MUESTRE LAS SIGUIENTES OPCIONES.-
	1.-LEER DESDE TECLADO.
	2.-LEER DESDE FICHERO.
	3.-ESCRIBIR EN FICHERO.
	4.-SALIR.
	
	TECLEANDO 1 NOS PEDIRÁ QUE LE INTRODUZCAMOS UN TEXTO Y ESTA LA 
	IMPRIMIREMOS POR PANTALLA INDICANDO AL FINAL DE LA FRASE “GRACIAS POR LA 
	FRASE”.
	
	TECLEANDO 2 NOS PEDIRÁ EL NOMBRE/RUTA DEL FICHERO A LEER E IMPRIMIREMOS 
	TO-DO EL FICHERO POR PANTALLA.
	
	TECLEANDO 3 NOS PEDIRÁ EL NOMBRE/RUTA DEL FICHERO A ESCRIBIR Y NOS PEDIRÁ 
	QUE INTRODUZCAMOS UN TEXTO POR PANTALLA, QUE LUEGO ESCRIBIREMOS EN EL 
	FICHERO.
	
	TECLEANDO 4 FINALIZARÁ EL PROGRAMA. MIENTRAS NO FINALICEMOS SEGUIRÁ 
	MOSTRANDO EL MENÚ PARA VOLVER A REALIZAR TAREAS.
 * */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main 
{

	public static void main(String[] args) throws NumberFormatException, IOException 
	{
		boolean exit = false;
		
		while (!exit)
		{
			Draw();
			
			int option = getOption();
			
			switch(option)
			{
				case 1:
					Show();		
					break;
				case 2:
					ReadFile();
					break;
				case 3:
					WriteFile();
					break;
				case 4:
					System.out.println("Bye!");
					exit = true;
					break;
				default:
					System.out.println("Error, '" + option + "' opción no reconocida por el sistema");
					break;
			}
		}
	}
	
	
	// Dibuja el menu en pantalla
	public static void Draw()
	{
		System.out.println("1.-LEER DESDE TECLADO.");
		System.out.println("2.-LEER DESDE FICHERO.");
		System.out.println("3.-ESCRIBIR EN FICHERO.");
		System.out.println("4.-SALIR.");
		System.out.println();
		System.out.print("Introduzca una opción: ");
	}
	
	
	public static int getOption() throws NumberFormatException, IOException
	{
		InputStreamReader c = new InputStreamReader(System.in); 
		BufferedReader in = new BufferedReader(c);
	
		int option = Integer.parseInt(in.readLine());
		
		return option;
	}
	
	
	// Pedir cadena y mostrarla por pantalla concatenando
	public static void Show() throws IOException
	{
		System.out.print("Introduzca un texto: ");
		
		InputStreamReader c = new InputStreamReader(System.in); 
		BufferedReader in = new BufferedReader(c);
		
		System.out.println(in.readLine() + " GRACIAS POR LA FRASE.");
		System.out.println();
	}

	
	// Pedir ruta archivo y mostrarlo en pantalla
	public static void ReadFile() throws IOException 
	{
		System.out.print("Introduzca el nombre/ruta de un fichero a leer: ");
		
		InputStreamReader c = new InputStreamReader(System.in); 
		BufferedReader in = new BufferedReader(c);
		
		File file = new File(in.readLine());
		
		FileReader fr = new FileReader(file);
		in = new BufferedReader(fr);
		
		String line = "";
		while (line != null)
		{
			line = in.readLine();
			
			if (line != null) System.out.println(line);
		}
		
		fr.close();
		
		System.out.println();
	}

	
	// Pedir ruta archivo y pedir texto para escribirlo en fichero
	public static void WriteFile() throws IOException
	{
		System.out.print("Introduzca el nombre del fichero a escribir: ");
		
		InputStreamReader c = new InputStreamReader(System.in); 
		BufferedReader in = new BufferedReader(c);
		
		File file = new File(in.readLine());
		
		FileWriter fw = new FileWriter(file);
		in = new BufferedReader(new InputStreamReader(System.in));
		
		String line = "";
		System.out.println("El archivo se guardará automaticamente cuando pulse enter y no escriba nada.");
	
		do
		{
			line = in.readLine();
			
			if (line.length() > 0) fw.write(line + "\r\n");
		}
		while (line.length()>0);
		
		
		fw.close();
		
		System.out.println();
	} 
	
}

Ejercicio 3

// Autor: Juan Antonio Ripoll
// Fecha: 03/10/13

// Descripción:
/*
   REALIZA UN PROGRAMA QUE LEA CARÁCTER A CARÁCTER DE UN FICHERO QUE SE LE 
   PASE COMO PARAMETRO, Y CONVIERTA A MAYÚSCULAS EN EL FICHERO TODAS LAS 
   LETRAS “a”. UTILIZA LA CLASE RANDOMACCESSFILE.
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;


public class Main 
{
	public static void main(String[] args) throws IOException 
	{		
		File file;
		
		if (args.length != 1)
		{
			InputStreamReader c = new InputStreamReader(System.in); 
			BufferedReader in = new BufferedReader(c);
			
			System.out.print("Introduzca la ruta del archivo: "); 
			file = new File( in.readLine() );
		}
		else
			file = new File( args[0] );
		
		
		RandomAccessFile randomAccessFile = new RandomAccessFile( file, "rw" );
		
		System.out.println("Buscando coincidencias en archivo ...");
		
		for (int i=0;i

Ejercicio 2

/*
 // Autor: Juan Antonio Ripoll
// Fecha: 03/10/2013

// Descripción:
/*
   REALIZA UN PROGRAMA EN JAVA QUE HAGA UNA COPIA DE UN FICHERO A OTRO DE 
   TODOS SUS DATOS. LOS NOMBRES DEL FICHERO A COPIAR SE LE PASARÁN COMO 
   PARÁMETRO.
*/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main 
{
 public static void main(String[] args) throws IOException 
 {
  File file_in;
  File file_out;
  
  if (args.length != 2)
  {
   InputStreamReader c = new InputStreamReader(System.in); 
   BufferedReader in = new BufferedReader(c);
   
   System.out.print("Introduzca la ruta del archivo a copiar: "); 
   file_in = new File( in.readLine() );
   
   System.out.print("Introduzca la ruta del nuevo archivo: "); 
   file_out = new File( in.readLine() );
  }
  else
  {
   file_in = new File( args[0] );
   file_out = new File( args[1] );
  }
 
  System.out.println("Realizando copia de fichero un momento ...");
  
  try 
  {
   FileInputStream in = new FileInputStream(file_in);
   FileOutputStream out = new FileOutputStream(file_out);
   
   int i = 0;
   while(i != -1)
   {
    i = in.read();
    
    if (i != -1) out.write(i);
   }
   
   in.close(); out.close();
   
   System.out.println("La copia se realizó correctamente.");
  }
  catch(IOException e) 
  { 
   System.out.println("Error intentado realizar la copia del archivo.");
  }
 }

}

Ejercicio 1

/*
 * Autor: Juan Antonio Ripoll
 * 
 * REALIZA UN PROGRAMA EN JAVA QUE MUESTRE LOS FICHEROS DE UN DIRECTORIO. EL 
 * NOMBRE (DEL FICHERO O DIRECTORIO) SE PASARÁ COMO PARÁMETRO.
*/

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class Main 
{
 public static void main(String[] args) throws IOException 
 {
  String path_file = null;
  
  if (args.length != 1)
  {
   System.out.print("Introduzca la ruta de un directorio/archivo: "); 
   
   InputStreamReader c = new InputStreamReader(System.in); 
   BufferedReader in = new BufferedReader(c);
   
   path_file = in.readLine();
  }
  else 
   path_file = args[0];
  
  
  File archivo = new File( path_file );
  
  if (archivo.isDirectory())
  {
   File[] archivos = archivo.listFiles();
   
   for (File a : archivos) {
    System.out.println(a.getName());
   } 
  }
 }
}

Wednesday, October 30, 2013

2.07 - Repeat until 0 do while

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Create a JAVA program to ask the user for a number "x" and display 10*x. 
 * It must repeat until the user enters 0 (using "do-while"). 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  int number;
     do
     {
      System.out.print("Enter a number: ");
         number = in.nextInt();
         
      System.out.println(number*10); 
     }
     while (number != 0);
 }
}

2.06 - Repeat until 0

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Create a JAVA program to ask the user for a number "x" 
 * and display 10*x. It must repeat until the user enters 0 (using "while"). 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a number: ");
  int number = in.nextInt();
  
     while (number != 0)
     {
      System.out.println(number*10);
      
      System.out.print("Enter a number: ");
         number = in.nextInt();
     }
 }
}

2.05 - Greatest of three numbers

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to get three numbers 
 * from the user and display the greatest one. 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter the first number: ");
  int number1 = in.nextInt();
  
  System.out.print("Enter the second number: ");
  int number2 = in.nextInt();
  
  System.out.print("Enter the third number: ");
  int number3 = in.nextInt();
  
  
  if (number1 > number2)
   if (number1 > number3)
    System.out.println("The greatest: " + number1);
  
  if (number2 > number1)
   if (number2 > number3)
    System.out.println("The greatest: " + number2);
  
  if (number3 > number1)
   if (number3 > number2)
    System.out.println("The greatest: " + number3);
 }
}

2.04 - Divide if not zero using else

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for two numbers, and show 
 * their division if the second number is not zero; otherwise, 
 * it will display "I cannot divide 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter the first number: ");
  int number1 = in.nextInt();
  
  System.out.print("Enter the second number: ");
  int number2 = in.nextInt();
  
  
  if (number2!=0)
   System.out.print(number1 + " / " + number2 + " = " 
      + number1/number2);
  else
   System.out.print("I cannot divide.");
 }
}

2.03 - Divide if not zero

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for two numbers, and show 
 * their division if the second number is not zero; otherwise, 
 * it will display "I cannot divide 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter the first number: ");
  int number1 = in.nextInt();
  
  System.out.print("Enter the second number: ");
  int number2 = in.nextInt();
  
  
  if (number2!=0)
   System.out.print(number1 + " / " + number2 + " = " 
      + number1/number2);
  else
   System.out.print("I cannot divide.");
 }
}

2.02 - Multiply if not zero

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for a number; if it is not zero, 
 * then it will ask for a second number and display their product; 
 * otherwise, it will display "0".
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter the first number: ");
  int number1 = in.nextInt();
  
  if (number1!=0)
  {
   System.out.print("Enter the second number: ");
   int number2 = in.nextInt();
    
   System.out.print(number1 + " X " + number2 + " = " 
      + number1*number2);
  }
  else
   System.out.print(number1);
 }
}

2.01 - Positive and negative

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to get a number from the and 
 * answer whether it is positive or negative.
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a number: ");
  int number = in.nextInt();
  
  if (number>0)
   System.out.println(number + " is positive.");
  
  if (number<0)
   System.out.println(number + " is negative.");
 }
}

1.14 - Conversion

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Create a JAVA program to convert from celsius degrees to Kelvin 
 * and Fahrenheit: it will ask the user for the amount of celsius degrees 
 * and using the following conversion tables: 

   kelvin = celsius + 273 
   fahrenheit = celsius x 18 / 10 + 32 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter the amount of celsius: ");
  int celsius = in.nextInt();
  
  System.out.println("Kelvin = " + celsius + 273);
  System.out.println("Fahrenheit = " + celsius * 18 / 10 + 32);
 }
}

1.13 - Rectangle

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for a number and 
 * then display a rectangle 3 columns wide and 5 rows tall 
 * using that digit. For example: 

   Enter a digit: 3 
   333 
   3 3 
   3 3 
   3 3 
   333  
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a digit: ");
  int digit = in.nextInt();
  
  for (int row=0;row<5;row++)
  {
   for (int column=0;column<3;column++)
   {
    if (row == 0 || row == 4)
     System.out.print(digit); 
    else
    {
     if (column == 1)
      System.out.print(" "); 
     else
      System.out.print(digit); 
    }
   }
   System.out.println();
  }
 }
}

1.12 - Formats

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for a number and display 
 * four times in a row, separated with blank spaces, 
 * and then four times in the next row, with no separation.  
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a digit: ");
  int digit = in.nextInt();
  
  System.out.println(digit + " " + digit + " " + digit + " " + digit);
  System.out.println(digit + "" + digit + "" + digit + "" + digit);
 }
}

1.11 - Age

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for three numbers (a, b, c) 
 * and display the result of (a+b)·c and the result of a·c + b·c  
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a number a: ");
  int number1 = in.nextInt();
  
  System.out.print("Enter a number b: ");
  int number2 = in.nextInt();
  
  System.out.print("Enter a number c: ");
  int number3 = in.nextInt();
  
  
  System.out.println("(a+b)·c = " + (number1 + number2) * number3);
  System.out.println("a·c + b·c = " + ( (number1 * number3) + (number2*number3) ));
 }
}

1.10 - Equivalent operations

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for his age 
 * (20, for instance) and answer something as "You look younger than 20" 
 * (instead of 20, you should display the age that has been entered). 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a age: ");
  int age = in.nextInt();
  
  System.out.println("You look younger than " + age + ".");
 }
}

1.09 - Average

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to calculate and display the average 
 * of four numbers entered by the user. 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a number1: ");
  int number1 = in.nextInt();
  
  System.out.print("Enter a number2: ");
  int number2 = in.nextInt();
  
  System.out.print("Enter a number3: ");
  int number3 = in.nextInt();
  
  System.out.print("Enter a number4: ");
  int number4 = in.nextInt();
  
  
  System.out.println("Average: " + 
   (number1 + number2 + number3 + number4) / 4);
 }
}

1.08 - Multiplication table

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for a number and 
 * display its multiplication table, like this: 

   5 x 1 = 5 
   5 x 2 = 10 
   5 x 3 = 15 
   ... 
   5 x 10 = 50 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a number: ");
  int number1 = in.nextInt();
  
  for (int i=0; i<10;i++){
   System.out.println(number1 + " x " + (i+1) + " = " + 
     (number1 * (i+1)));
  }
 }
}

1.07 - Several operations

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to print on screen the result of adding, 
 * subtracting, multiplying and dividing two numbers typed by the user. 
 * The remainder of the division must be displayed, too. 

   It might look like this: 

   Enter a number: 12 
   Enter another number: 3 
   12 + 3 = 15 
   12 - 3 = 9 
   12 x 3 = 36 
   12 / 3 = 4 
   12 mod 3 = 0 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a number: ");
  int number1 = in.nextInt();
  
  System.out.print("Enter another number: ");
  int number2 = in.nextInt();
  

  System.out.println(number1 + " + " + number2 + " = " + 
  (number1 + number2));
  
  System.out.println(number1 + " - " + number2 + " = " + 
  (number1 - number2));
  
  System.out.println(number1 + " x " + number2 + " = " + 
  (number1 * number2));
  
  System.out.println(number1 + " / " + number2 + " = " + 
  (number1 / number2));

  System.out.println(number1 + " mod " + number2 + " = " + 
  (number1 % number2));
 }

}

1.06 - Use of comments

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to ask the user for three numbers 
 * and display their multiplication. 
 * The first line must be a comment with your name and surname. 
 * It MUST look as follows: 

   Enter the first number to multiply 
   12 
   Enter the second number to multiply 
   23 
   Enter the third number to multiply 
   2 
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.println("Enter the first number to multiply");
  int number1 = in.nextInt();
  
  System.out.println("Enter the second number to multiply");
  int number2 = in.nextInt();
  
  System.out.println("Enter the third number to multiply");
  int number3 = in.nextInt();
  
  System.out.println(number1 + " x " + number2 + " x " + number3 + " = " + 
    number1 * number2 * number3);
 }

}

1.05 - Multiple operations and precedence

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to print the result of multiplying two numbers which 
 * will entered by the user.
 * */

import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter 1st number: ");
  int number1 = in.nextInt();
  
  System.out.print("Enter 2st number: ");
  int number2 = in.nextInt();
  
  System.out.println(number1 + " x " + number2 + " = " + number1 * number2);
 }

}

1.04 - Multiple operations and precedence

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Create a JAVA program to print the result of the following operations: 

   • -1 + 3 * 5 
   • (24+5) % 7 
   • 15 + -4*6 / 11 
   • 2 + 10 / 6 * 1 - 7 % 2   
 * */

public class Main {

 public static void main(String[] args) {
  System.out.println(-1+3*5);
  System.out.println((24+5) % 7);
  System.out.println(15+-4*6/11);
  System.out.println(2+10/6*1-7%2);
 }

}

1.03 - Division of two numbers

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to print the result of 
 * dividing 24 into 5 on screen.  
 * */

public class Main {

 public static void main(String[] args) {
  System.out.println(24/5);
 }

}

1.02 - Sum two numbers

/*
/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Write a JAVA program to print the result of 
 * adding 12 and 13 on screen.  
 * */

public class Main {

 public static void main(String[] args) {
  System.out.println(12+13);
 }

}

1.01 - First program in JAVA

/*
 * Autor: Juan Antonio Ripoll
 * Date: 30/10/13
 * 
 * Create a program (in JAVA) to print Hello on screen 
 * and then print your name (in a separate line).
 * */

public class Main {

 public static void main(String[] args) {
  System.out.println("Hello\nJuan!");
 }

}