Obtener mayor valor de un arreglo de enteros
Java
1.052 visualizaciones desde el 11 de Diciembre del 2020
Dado un arreglo de enteros, no vacio, obtener el valor mayor contenido en el.
import java.util.Arrays;
public class Main
{
private static int mayor(int valores[]) {
if( valores == null || valores.length == 0) {
throw new IllegalArgumentException("Sin datos, no hay mayor");
}
int mayor = valores[0];
for(int valor: valores) {
if( valor > mayor ) {
mayor = valor;
}
}
return mayor;
}
public static void testMayor(int valores[], int valorEsperado) {
int valorObtenido = mayor(valores);
System.out.print( "mayor( " + Arrays.toString(valores) + " ) = " + valorObtenido + " ");
if( valorObtenido == valorEsperado ) {
System.out.println("\tOK");
} else {
System.out.println("\tERROR, se esperaba " + valorEsperado );
}
}
public static void main(String[] args) {
testMayor( new int[] { 1, 2, 3, 4 }, 4); // Arreglo creciente
testMayor( new int[] { 4, 3, 2, 1 }, 4); // decreciente
testMayor( new int[] { 2, 1, 4, 3 }, 4); // arriba, abajo
testMayor( new int[] { 4, 4, 4, 4 }, 4); // todos iguales
testMayor( new int[] { 123 }, 123 ); // solo 1 valor
testMayor( new int[] { -4, -3, -2, -1 }, -1); // valores negativos
testMayor( new int[] { -4, 3, -2, 1 }, 3); // valores positivos y negativos
testMayor( new int[] { 200, 100, 400, 300 }, 400); // valores mas grandes
}
}
Comentarios sobre la versión: 1.0 (0)
No hay comentarios