Universidad Carlos III de Madrid

Ingeniería de Telecomunicación

Enero-Mayo 2010 / January-May 2010

Orientación a Objetos y Herencia (I)

Lab Section1. Laboratorio: Repaso

TimeTOTAL: 90 min

Exercise Section1.1. Conceptos Básicos Java

Time20 min

Objetivo

Comprobar si se conocen ciertos conceptos clave de Java.

Ejercicio

Responde por escrito a las siguientes preguntas:

  • ¿Qué editor de textos vas a usar para crear los fuentes de sus programas? ¿Sabes usarlo?

  • ¿Cuál es el PATH del compilador java que vas a usar en las prácticas?

  • ¿Qué opción del compilador te parece más inútil?

  • ¿Qué versión de la JRE se usará en las prácticas?

  • ¿Cuál es el PATH de la máquina virtual Java?

  • ¿Cuál es la URL oficial para la API de dicha JRE?

  • ¿Sabes lo que es Java EE, Java SE y Java ME?

  • ¿Cuál es la diferencia entre parámetros formales y parámetros actuales?

  • ¿Qué es un programa?

  • ¿Entiendes la diferencia entre tipo y valor?

  • ¿Entiendes la diferencia entre clase y objeto?

  • ¿Hay equivalencia entre clase y tipo?

  • ¿Hay equivalencia entre objeto y valor?

  • ¿Entiendes la diferencia entre referencia a objeto y objeto?

  • ¿Qué hace el "recolector de basura" ("garbage collector")?

  • ¿Qué diferencia hay entre un método de clase y un método de objeto?

  • ¿Qué diferencia hay entre un atributo y una variable?

Solución

No aplica. Preguntad al profesor.

Exercise Section1.2. Repaso al método main

Time20 min

Objetivo

Repaso del método main y su utilidad.

Ejercicio

A continuación se presentan una serie de preguntas sobre el método main que deberá contestar por escrito y en los casos en los que sea necesario comprobar su funcionamiento.

  • ¿A qué se debe la existencia del método main?

  • ¿Entiende la función de un sistema operativo? ¿Qué relación existe entre el sistema operativo y el método main?

  • Si lanzamos el comando java Clase y Clase no implementa método main ¿qué ocurre? ¿entiende bien el mensaje por pantalla?

  • Si un programa en Java tiene cinco clases y todas ellas implementan un método main, ¿podremos ejecutar cualquiera de las clases? o ¿Java sólo permite un método main por programa?

  • ¿Por qué razón es estático el método main?

  • ¿Puedo llamar desde el método main a otros métodos implementados en la clase?

  • ¿Por qué motivo sólo puedo llamar a métodos estáticos de la propia clase desde el método main?

  • Si el objetivo de método main es arrancar el programa, ¿cree qué es una buena prática de programación implementar más de 20 líneas de código en él?

  • ¿Cuál es la conexión entre el sistema operativo y el parámetro del método main?

  • ¿Por qué tengo un sólo parámetro y sin embargo desde el sistema operativo puedo ofrecerle al método main N valores a ese parámetro?

  • Aunque el método main no retorna valor ¿podría ser interesante devolver un valor al sistema operativo en la ejecución de main?

  • Explique el motivo por el que se define el parámetro de main como String [] args y no como String [255] args

Solución

No aplica. Preguntar al profesor

Exercise Section1.3. Pintado de Tablero de Ajedrez en modo consola

Time20 min

Objetivo

Practicar los bucles for.

Ejercicio

Implemente un programa que dibuje un ajedrez en modo consola al estilo:

	   
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB

	 

Solución

La solución se puede ver en el siguiente listado:

/**
 * Carlos III University, Madrid
 *
 */


/**
 *
 * Prints a chess board out the console
 */

class ChessBoard
{
  // Chess board as a 2-dimensional array
  public void prints()
  {
    char board[][] = new char[8][8];
    char cell = '0';

    for (int row = 0; row < 8; row++)
    {
      for (int column = 0; column < 8; column++)
      {
        if (column == 0)
        {
          if (row % 2 == 0)
          {
            // Black
        	  cell = 'B';
          }
          else
          { // White
        	  cell = 'W';
          }
        }
        else
        {
          if (cell == 'W')
        	  cell = 'B';
          else
        	  cell = 'W';
        }

        board[row][column] = cell;
      }
    }

    // Prints out
    for (int row = 0; row < 8; row++)
    {
      for (int column = 0; column < 8; column++)
      {
        System.out.print(board[row][column]);
      }
      System.out.println();
    }
  }

  // Testing
  public static void main(String args[])
  {
    ChessBoard t = new ChessBoard();
    t.prints();
  } //main

} // ChessBoard

	  

Resultando un error de compilación de este estilo: Main.java:7: Figura is abstract; cannot be instantiated Figura f = new Figura(Figura.BLANCO);

Exercise Section1.4. Transformación de bucles (for -> while)

Time15 min

Objetivo

Practicar con bucles.

Ejercicio

Transformar el siguiente bucle for en un bucle while:

for (int i=0;i<10;i++)
{
	System.out.print(i);
}
System.out.println("");

Solución

La solución se puede ver en el siguiente listado:

public class For2While
{

	public static void main(String [] args)
	{
	
		// loop for
		for (int i=0;i<10;i++)
		{
			System.out.print(i);
		}
		System.out.println("");
		
		// loop while
		int j = 0;
		while (j<10)
		{
			System.out.print(j);		
			j++;
		}
		System.out.println("");	
	}

} // For2While

Exercise Section1.5. Transformación de bucles (while -> for)

Time15 min

Objetivo

Practicar con bucles.

Ejercicio

Transformar el siguiente bucle while en un bucle for:

int [] items = { 2, 4, 6, 8, 10, 9, 7, 5, 3, 1};
boolean found = false;
int     find  = 10;
		
// loop while
int i = 0;
while ((!found) && (i<MAX_ITEMS))
{
	found = (items[i]==find);		
	i++;
}	
System.out.println(i-1);

Solución

La solución se puede ver en el siguiente listado:

public class While2For
{
	public final static int MAX_ITEMS = 10;
	
	public static void main(String [] args)
	{
		int [] items = { 2, 4, 6, 8, 10, 9, 7, 5, 3, 1};
		boolean found = false;
		int     find  = 10;
		
		// While loop
		int i = 0;
		while ((!found) && (i<MAX_ITEMS))
		{
			found = (items[i]==find);		
			i++;
		}	
		System.out.println(i-1);
		
		// loop for
		int j = 0;
		for (j=0;j<MAX_ITEMS;j++)
		{
			if (items[j]==find)
			{	
				found = true;
				break;
			}
		}
		System.out.println(j);		
	}
} // While2Java

Homework Section2. Actividades para casa

Time120 min

Exercise Section2.1. Ejercicios de repaso de arrays

Time30 min

Objetivo

Repaso de arrays con ejercicios muy básicos.

Ejercicio

  • Devolver el mayor de los números enteros de un array.

  • Devolver la media de los elementos de un array.

  • Mostrar los elementos pares de un array.

  • Mostrar el sumatorio de los elementos de un array.

Solución

La solución se puede ver en el siguiente listado:

/**
 * Carlos III University, Madrid
 * 
 */


/**
 *
 * Arrays review
 */

class ArraysReview
{

  /** Calculates the biggest integer */
  public void exercise1()
  {
    int elements [] = new int[200];

    // Fills the array
    for (int i=0;i<200;i++)
    {
         elements[i] = i+1;
    }

    // Calculates the biggest number
    int biggest = Integer.MIN_VALUE;
    for (int i=0;i<200;i++)
    {
         if (elements[i]>biggest)
         {
        	 biggest = elements[i];
         }
    }
    System.out.println("The biggest is: " + biggest);
  } // Exercise 1


   // Mean of the elements
   public void exercise2()
   {
     long elements [] = new long[200];

     // Fills the array
     for (int i=0;i<200;i++)
     {
       elements[i] = i+1;
     }

     // Summation of the elements
     long sum = 0;
     for (int i=0;i<200;i++)
     {
    	 sum = sum + elements[i];
     }
     // Don't forget to change the type due to the precision
     double mean = (double)sum/(double)200;
     System.out.println("The mean is: " + mean);
    } // exercise2

    // Shows the even elements in the array
    public void exercise3()
    {
       int elements [] = new int[200];

       // Fills the array
       for (int i=0;i<200;i++)
       {
            elements[i] = i+1;
       }

       // Prints the even elements
       for (int i=0;i<200;i++)
       {
            if (elements[i] % 2 == 0)
                     System.out.println(elements[i]);
       }
    } // exercise3


    // Summation of the elements
    public void exercise4()
    {
        long elements [] = new long[200];

        // Fills the array
        for (int i=0;i<200;i++)
        {
                elements[i] = i+1;
        }

        // Sum all the elements
        long sum = 0;
        for (int i=0;i<200;i++)
        {
        	sum = sum+ elements[i];
        }
        System.out.println("The summation is: " + sum);
     } // Exercise4


     // Testing
     public static void main(String args[])
     {
        ArraysReview r = new ArraysReview();
        r.exercise1();
        r.exercise2();
        r.exercise3();
        r.exercise4();
     } // main

} // ArraysReview

	  

Exercise Section2.2. Indicar si una frase o palabra es palíndroma

Time25 min

Objetivo

Repaso de bucles.

Ejercicio

Una palabra o frase es palíndroma si se lee igual de izquierda a derecha que de derecha a izquierda. Implemente un programa que permita determinar si una cadena dada es palíndroma o no.

Solución

Una posible solución se lista a continuación:

/**
 * Carlos III University, Madrid
 * Systems Programming.
 *  
 * Program that detects if a word or sentence is palindrome.
 */


/**
 *
 * Palindrome class.
 */
public class Palindrome
{

    /**
     * Detects if a word or sentence is palindrome
     * @param string String
     * @return boolean
     */
    public boolean isPalindrome(String string)
    {
        // By default, string is palindrome
        boolean isPalin = true;
        // To detect the end of the loop -the end of the string-.
        boolean end = false;
        // Convert the characters to lower-letters and omit the blank characters to avoid problems
        String normalizedString = string.replaceAll(" ","");
        normalizedString = normalizedString.toLowerCase();

        // Initialize the position in left and right ends
        int left_to_right = 0;
        int right_to_left = normalizedString.length() - 1;

        // Go along the string
        while ((isPalin) && (!end))
        {
            // Compare the characters
        	isPalin = (normalizedString.charAt(left_to_right) == normalizedString.charAt(right_to_left));
            
        	left_to_right++;
        	right_to_left--;

            // Check if we have finished.
            end = ((right_to_left == -1) || (left_to_right ==normalizedString.length()));
        }

        return isPalin;
    }

    public static void main(String [] args)
    {
        boolean palindrome = false;
        Palindrome p = new Palindrome();

        System.out.println("==========");
        System.out.println("PALYNDROME");
        System.out.println("==========");

        palindrome = p.isPalindrome("Ana");
        System.out.println("Ana: " + palindrome);

        palindrome = p.isPalindrome("Level");
        System.out.println("Level: " + palindrome);
        
        palindrome = p.isPalindrome("Si a la ingenieria telematica");
        System.out.println("Si a la ingenieria telematica: " + palindrome);

        palindrome = p.isPalindrome("Dabale arroz a la zorra el abad");
        System.out.println("Dabale arroz a la zorra el abad: " + palindrome);
        
        palindrome = p.isPalindrome("Satan oscillate my metallic sonatas");
        System.out.println("Satan oscillate my metallic sonatas: " + palindrome);
        
    }


} // Palindrome

	  

Exercise Section2.3. Cálculo del factorial mediante bucles

Time15 min

Objetivo

Prácticar con bucles.

Ejercicio

Implementar el cálculo del factorial de un número dado primero utilizando un bucle for y después utilizando un bucle while.

Solución

La solución se puede ver en el siguiente listado:

/**
 * Class to calculate factorials
 */
class FactorialEx {

   // FOR-BASED SOLUTION
   /**
    * Calculates the factorial of an integer with a 'for' loop
    *
    * @param n Integer whose factorial is going to be calculated
    * @return Factorial of the integer 'n'
    */
   public static int fact( int n ) {
    
      int result = 1;

      for (int i = 1; i <= n; i++) {
    	  result *= i;
      }

      return result;
   }
   
   // WHILE-BASED SOLUTION
   /**
    * Calculates the factorial of an integer with a 'while' loop
    * 
    * @param n Integer whose factorial is going to be calculated
    * @return Factorial of the integer 'n'
    */
   public static int factWhile( int n ) {
    
      int result = 1;
      
      int i = 1;
      while ( i <= n ) {
    	  result *= i;
         i++; // The auto-increment statement can also be stated in the 'while' condition
      }

      return result;
   }
   
   // SOLUTION WITH DO-WHILE LOOP  
  
  
   /**
    * Main method, for testing purpose
    * The program gets as argument the number whose factorial is going
    * to be calculated.
    */
   public static void main(String[] args) {
    
      // Integer variables to store the number and the factorial result
      int number;
      int result;

      // Exceptions are managed (try-catch block)       
      try {
         // Gets the number whose factorial is going to be calculated
         number = new Integer( args[0] ).intValue();
          
          
         // Factorial with for loop
         System.out.println( "Testing 'for' loop:" );    
          
         // Prints the beginning of the message
         System.out.print(number + "! = ");
          
         // Calculates the factorial
         result = fact(number);
          
         // Prints the result
         System.out.println(result + "\n");          
          
         // Factorial with while loop
         System.out.println( "Testing 'while' loop:" );
          
         // Prints the beginning of the message
         System.out.print(number + "! = ");
          
         // Calculates the factorial
         result = factWhile( number );
          
         // Prints the result
         System.out.println(result + "\n");
         
      } catch ( Exception e ) {
         // error
         System.out.println( "Error: An integer number was expected" );
      }
      
  }
  
}


	  

Exercise Section2.4. Arrays de 2 dimensiones

Time30 min

Objetivo

Practicar ejercicios de arrays (2 dimensiones).

Ejercicio

Implemente un clase Matriz con el comportamiento para la suma de matrices, teniendo en cuenta que el resultado de la suma no podrá modificar la instancia sobre la que se ejecuta el método.

Aclaración

El número de filas y columnas de la matriz deberá indicarse en el momento de creación del objeto.

Solución

La solución se puede ver en el siguiente listado:

/**
 * <p>This class encapsulates the behavior of a matrix formed by integer numbers.
 * Implemented characteristics:
 *    - Number of rows and columns can be defined
 *    - Inicialization element can be defined
 *    - Offers a 'sum' function without modifying the matrix object 
 *   
 * </p>
 *
 * @author UC3M - Telematics Department
 * @version 1.0
 */
public class Matrix
{
    /** Where elements are stored */
    private int elements[][];
    private int rows;
    private int columns;

    /** Object constructor, taking into account rows and columns */
    public Matrix(int rows, int columns, int initElement)
    {
        elements = new int[rows][columns];
        this.rows = rows;
        this.columns = columns;

        // Initialization
        for (int row=0;row<rows;row++)
            for (int column = 0; column < columns; column++)
                elements[row][column] = initElement;

    }

    /** Sums to the current matrix another 'm' matrix, returning the resulting one */
    /** It neither modifies the current matrix nor the second one which is added to the current one*/
    public Matrix sum(Matrix m) throws Exception
    {
        // We check the necessary conditions to sum the two matrix.
        if (this.rows != m.rows)
            throw new Exception ("Error: Matrixes with different number of rows cannot be sumed");

        if (this.columns != m.columns)
            throw new Exception ("Error: Matrixes with different number of rows cannot be sumed");

        Matrix aux = new Matrix(this.rows,this.columns,0);
        for (int row=0;row<rows;row++)
            for (int column = 0; column < columns; column++)
                aux.elements[row][column] =
                       this.elements[row][column] +
                       m.elements[row][column];
        return aux;
    }


    /** Testing the results */
    public void print()
    {
        for (int row=0;row<rows;row++)
        {
            for (int column = 0; column < columns; column++)
            {
                System.out.print(elements[row][column] + "-");
            }
            System.out.println("");
         }
    }


    /** Testing */
    public static void main(String [] args)
    {
        Matrix m1, m2, m3, m4;
        m1 = new Matrix(2,3,1);
        m2 = new Matrix(3,2,2);
        m3 = new Matrix(2,3,3);

        try
        {
            m4 = m1.sum(m2);            
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }

        try
        {
            m4 = m2.sum(m3);
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }

        try
        {
            m4 = m1.sum(m3);
            System.out.println("m1:");
            m1.print();
            System.out.println("m3:");
            m3.print();
            System.out.println("m1+m3:");
            m4.print();
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }


} // Matrix

	  

Exercise Section2.5. Tratamiento de cadenas y clase Vector

Time20 min

Objetivo

Recorrer una cadena para trocearla y guardar cada parte como un elemento de un Vector.

Ejercicio

Implementar un programa que tenga un método que recibe una cadena de caracteres. Esa cadena de caracteres estará formada por subcadenas separadas por un carácter '|'.

Esta cadena de caracteres se debe descomponer para ir almacenando cada subcadena de forma individual en un objeto Vector. El método deberá devolver este objeto Vector.

La cadena puede estar vacía.

En el caso de que no sepa utilizar un Vector hágalo descomponiendo la cadena en un array donde cada posíción del array almacenará una subcadena.

Por ejemplo, la cadena "Si|No|A veces" debe descomponerse en las tres subcadenas: "Si", "No", "A veces", almacenada cada una de ellas por separado en el Vector (o array).

Aclaración

Puede encontrar información de la clase Vector en el siguiente archivo: Vector.pdf

Solución

La solución se puede ver en el siguiente listado:

import java.util.Enumeration;
import java.util.Vector;

/**
  *
  * <p>String usages</p>
  *
  * @author UC3M Telematics Department
  * @version 1.0
  */
class MyString
{
	/**
	* Function which splits a string formed by substrings separated by
	* |, such as "Yes|No|Sometimes"
	* @param myString String String with the previous format
	* @return Vector Vector storing each of the substrings.
	*/
	public Vector split(String string)
	{
		Vector v = new Vector();
		String aux = "";
		for (int i=0; i<string.length();i++)
		{
			if (string.charAt(i) != '|')
			{
				aux += string.charAt(i);
			}
			else
			{
				v.add(aux);
				aux = "";
			}
		}
		//For the last substring.
		v.add(aux);
		return v;
	}
} // MyString

/** Class testing*/
public class Strings
{
	public static void main(String [] args)
	{
		MyString myString = new MyString();
		Vector v = myString.split("Yes|No|Sometimes");
		// Example of vector iteration
		Enumeration e = v.elements();
		while (e.hasMoreElements())
		{
			String s = (String)e.nextElement();
			System.out.println(s);
		}
	}
}