Universidad Carlos III de Madrid

Ingeniería de Telecomunicación

Enero-Mayo 2010 / January-May 2010

Review: Fundamentals of Java

Lab Section1.  Session 2 (lab): Review exercises

We advise the students to program according to usual Java conventions. The document Java Coding Guidelines presents a brief introduction to the most important conventions, as well as instructions on how to configure Eclipse according to them.

Exercise Section1.1.  Exercises about arrays

Objective

Review arrays with some basic exercises.

Exercise

  • Return the biggest integer number of an array of integers.

  • Return the average of the elements of an array.

  • Show the elements of an array that are even (divisible by 2).

  • Show the sumatory of the elements of an array.

Solution

The solution is included in the following listing:

public class ArraysReview {

  private int findLargest(int[] numbers) {
    int largest = Integer.MIN_VALUE;
    for (int i = 0; i < numbers.length; i++) {
      if (numbers[i] > largest) {
        largest = numbers[i];
      }
    }
    return largest;
  }

  private double findAverage(int[] numbers) {
    return ((double) calculateTotal(numbers)) / numbers.length;
  }

  private void printEven(int[] numbers) {
    for (int i = 0; i < numbers.length; i++) {
      if ((numbers[i] % 2) == 0) {
        System.out.println(i + ": " + numbers[i]);
      }
    }
  }

  private int calculateTotal(int[] numbers) {
    int total = 0;
    for (int i = 0; i < numbers.length; i++) {
      total += numbers[i];
    }
    return total;
  }

  public static void main(String[] args) {
    int[] numbers = new int[] { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3,
        2, 3, 8, 4, 6 };
    // Dump the array to check it is ok
    for (int i = 0; i < numbers.length; i++) {
      System.out.println(i + ": " + numbers[i]);
    }
    ArraysReview myReview = new ArraysReview();
    int mayor = myReview.findLargest(numbers);
    System.out.println("Largest: " + mayor);
    double mean = myReview.findAverage(numbers);
    System.out.println("Average: " + mean);
    myReview.printEven(numbers);
    System.out.println("Total: " + myReview.calculateTotal(numbers));
  }
}

	  

Exercise Section1.2.  Displaying a Chess Board in text format on console

Objective

Practice for loops.

Exercise

Implement a program that displays a text based Chess Board on the console (standard output) as follows:

        
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB

      

You must implement TWO SOLUTIONS. The first one must use just loops and commands to print on the screen. The second solution must create an array, fill it in with the appropriate values, and finally, display it on the screen.

Solution

One possible solution is included in the following listing:

public class Chessboard {
  private void printBoard() {
    for (int i = 0; i < 8; i++) {
      for (int j = 0; j < 8; j++) {
        if ((i + j) % 2 == 0) {
          System.out.print("B");
        } else {
          System.out.print("W");
        }
      }
      System.out.println();
    }
  }

  private void fillAndPrintBoard() {
    String[][] board = new String[8][8];
    for (int i = 0; i < 8; i++) {
      for (int j = 0; j < 8; j++) {
        if ((i + j) % 2 == 0) {
          board[i][j] = "B";
        } else {
          board[i][j] = "W";
        }
      }
    }
    for (int i = 0; i < 8; i++) {
      for (int j = 0; j < 8; j++) {
        System.out.print(board[i][j]);
      }
      System.out.println("");
    }
  }

  public static void main(String[] args) {
    Chessboard myBoard = new Chessboard();
    myBoard.printBoard();
    System.out.println("--------");
    myBoard.fillAndPrintBoard();
  }
}

        

Exercise Section1.3.  Loop conversion (for -> while)

Objective

Practice loops.

Exercise

Translate the following for loop into a while loop:

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

Solution

The solution is included in the following listing:

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

    // while
    int j = 0;
    while (j < 10) {
      System.out.print(j);
      j++;
    }
    System.out.println("");
  }

} // For2While

Exercise Section1.4.  Conversion of loops (while -> for)

Objective

Practice loops.

Exercise

Translate the following while loop into a for loop:

final int MAX_ITEMS = 10;

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);

Solution

The solution is included in the following listing:

public class While2For {

  public static void main(String[] args) {
    final int MAX_ITEMS = 10;

    int[] items = { 2, 4, 6, 8, 10, 9, 7, 5, 3, 1 };
    boolean found = false;
    int find = 10;

    // while
    int i = 0;
    while ((!found) && (i < MAX_ITEMS)) {
      found = (items[i] == find);
      i++;
    }
    System.out.println(i - 1);

    // for
    int j = 0;
    for (j = 0; j < MAX_ITEMS; j++) {
      if (items[j] == find) {
        found = true;
        break;
      }
    }
    System.out.println(j);
  }
} // While2For

Homework Section2.  Homework

Exercise Section2.1.  Check whether a phrase or a word is a palindrome

Objective

Review loops.

Exercise

A palindrome is a word or a phrase that is read the same forwards or backwards. Implement a program that determines whether a given string is a palindrome or not.

Solution

A possible solution is listed following:

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

public class Palindrome {

  /**
   * Detects if a word or sentence is palindrome
   * 
   * @param string
   *          String
   * @return boolean
   */
  public boolean isPalindrome(String string) {
    // Convert the characters to lowercase and skip the blank characters
    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 comparing the left position with the right position
    // If they do not match, it is not palindrome
    while (left_to_right <= right_to_left) {
      if (normalizedString.charAt(left_to_right) != normalizedString
          .charAt(right_to_left)) {
        return false;
      }
      left_to_right++;
      right_to_left--;
    }
    // If it leaves the loop, no mismatch has been found, so it is palindrome
    return true;
  }

  public static void main(String[] args) {
    String[] tests = { "abccba", "Ana", "Level",
        "Si a la ingenieria telematica", "Dabale arroz a la zorra el abad",
        "Satan oscillate my metallic sonatas" };
    Palindrome palindromeTester = new Palindrome();
    for (int i = 0; i < tests.length; i++) {
      System.out.println(tests[i] + ": "
          + palindromeTester.isPalindrome(tests[i]));
    }
  }

} // Palindrome
	  

Exercise Section2.2.  Calculation of factorial using loops

Objective

Practice loops.

Exercise

Implement a method that returns the factorial of a given number, first using a for loop and then using a while loop.

Solution

The solution is included in the following listing:

/**
 * Class to calculate factorial
 */
class Fact {

  /**
   * 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 int factFor(int n) {
    if (n < 0) {
      return -1;
    }
    int result = 1;
    for (int i = 1; i <= n; i++) {
      result *= i;
    }
    return result;
  }

  /**
   * 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 int factWhile(int n) {
    if (n < 0) {
      return -1;
    }
    int result = 1;
    int i = 1;
    while (i <= n) {
      result *= i;
      i++;
    }
    return result;
  }

  public static void main(String[] args) {
    int[] tests = new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, -1, -2 };
    Fact factTester = new Fact();
    for (int i = 0; i < tests.length; i++) {
      int number = tests[i];
      System.out.println("fact(" + number + ") = " + factTester.factFor(number)
          + " & " + factTester.factWhile(number));
    }
  }
}
	  

Exercise Section2.3.  2-dimension arrays

Objective

Practice with bi-dimensional arrays.

Exercise

Implement a class Matrix that includes a method for adding matrixes, taking into account that the result of the sum can not modify the instance over which the method is invoked.

Explanation

The number of rows and columns of the matrix must be given at the instance object's creation.

Solution

The solution is included in the following listing:

/**
 * 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
 * 
 * @author UC3M - Telematics Department
 * @version 1.0
 */
public class Matrix {
  /** Where elements are stored */
  private int elements[][];
  private int rows;
  private int columns;

  /**
   * Create an initialized matrix
   */
  public Matrix(int rows, int columns, int initElement) {
    elements = new int[rows][columns];
    this.rows = rows;
    this.columns = columns;
    for (int row = 0; row < rows; row++) {
      for (int column = 0; column < columns; column++) {
        elements[row][column] = initElement;
      }
    }
  }

  /**
   * Sets the value to the given position
   */
  public void set(int row, int column, int value) throws Exception {
    if ((row > this.rows) || (column > this.columns)) {
      throw new Exception("Out of bounds");
    }
    elements[row][column] = value;
  }

  /**
   * Gets the value to the given position
   */
  public int get(int row, int column) throws Exception {
    if ((row > this.rows) || (column > this.columns)) {
      throw new Exception("Out of bounds");
    }
    return elements[row][column];
  }

  /**
   * 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 add(Matrix m) throws Exception {
    // We check the necessary conditions to sum the two matrix.
    if ((this.rows != m.rows) || (this.columns != m.columns)) {
      throw new Exception(
          "Error: Matrixes with different sizes cannot be added");
    }
    Matrix res = new Matrix(this.rows, this.columns, 0);
    for (int row = 0; row < rows; row++) {
      for (int column = 0; column < columns; column++) {
        res.set(row, column, this.elements[row][column] + m.get(row, column));
      }
    }
    return res;
  }

  /** Testing the results */
  public String toString() {
    String res = "";
    for (int row = 0; row < rows; row++) {
      for (int column = 0; column < columns; column++) {
        res += elements[row][column] + " ";
      }
      res += "\r\n";
    }
    return res;
  }

  public void print() {
    System.out.println(toString());
  }

  /** Testing */
  public static void main(String[] args) {
    Matrix m1 = new Matrix(2, 3, 1);
    Matrix m2 = new Matrix(2, 3, 20);
    Matrix m3 = new Matrix(3, 3, 300);
    System.out.println("m1:");
    m1.print();
    System.out.println("m2:");
    m2.print();
    System.out.println("m3:");
    m3.print();

    try {
      Matrix m4 = m1.add(m2);
      System.out.println("m4:");
      m4.print();
    } catch (Exception ex) {
      System.out.println(ex);
    }

    try {
      // This operation must throw a exception, because they are different size
      Matrix m5 = m1.add(m3);
      System.out.println("m5:");
      m5.print();
    } catch (Exception ex) {
      System.out
          .println("If the following exception warns about different sizes, it is part of a correct test:");
      System.out.println(ex);
    }
  }

} // Matrix