Tabla de contenidos
Recomendamos a los estudiantes programar con un estilo que siga las convenciones habituales del lenguaje Java. El documento Directrices de Programación para Java presenta de forma breve las convenciones más importantes así como instrucciones para configurar Eclipse conforme a las mismas.
Repaso de arrays con ejercicios muy básicos.
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.
La solución se puede ver en el siguiente listado:
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));
}
}
Practicar los bucles for.
Implemente un programa que dibuje un ajedrez en modo consola al estilo:
BWBWBWBW WBWBWBWB BWBWBWBW WBWBWBWB BWBWBWBW WBWBWBWB BWBWBWBW WBWBWBWB
Debes escribir DOS SOLUCIONES. La primera debe utilizar bucles y comandos de impresión en pantalla. La segunda solución debe crear un array, rellenarlo convenientemente con los valores apropiados, y finalmente imprimirlo en pantalla.
Una posible solución se puede ver en el siguiente listado:
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(); } }
Practicar con bucles.
Transformar el siguiente bucle for
en un bucle while
:
for (int i = 0; i < 10; i++) { System.out.print(i); } System.out.println("");
La solución se puede ver en el siguiente listado:
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
Practicar con bucles.
Transformar el siguiente bucle while
en un bucle for
:
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);
La solución se puede ver en el siguiente listado:
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
Repaso de bucles.
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.
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.
*/
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
Prácticar con bucles.
Implementar el cálculo del factorial de un número dado primero utilizando un bucle for
y
después utilizando un bucle while
.
La solución se puede ver en el siguiente listado:
/**
* 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));
}
}
}
Practicar ejercicios de arrays (2 dimensiones).
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.
El número de filas y columnas de la matriz deberá indicarse en el momento de creación del objeto.
La solución se puede ver en el siguiente listado:
/**
* 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