Documente Academic
Documente Profesional
Documente Cultură
Hola que tal, esta vez vamos a ver que son los arreglos en
Java (vectores y matrices en Java). Los arreglos pueden ser
unidimensionales (también conocidos como vectores o
arrays), Multidimensionales (matrices) que pueden ser de 2
o 3 dimensiones.
Hasta ahora para poder almacenar información (de forma
temporal) y poder utilizarla en los programas, hemos
utilizado las variables, ya sea de tipo entero, String, double
etc.
Aprende este y otros temas de Programación Java
Web. Accede gratis al Curso de Java EE y suscribete al canal
de Youtube.
Si quieres profundizar sobre el tema de variables revisa esta
entrada Variables y tipos de datos en Java.
Bueno, con lo visto hasta ahora, digamos que queremos
almacenar 25 notas de estudiantes, esto requiere declarar 25
variables (algo razonable), pero ahora imaginemos que
necesitamos almacenar 100 o 1000 o 2000 notas, en este
caso tendremos que declara una variable para cada nota, en
total serían 100 o 1000 o 2000 variables, tedioso, confuso y
cansado, verdad?
El problema anterior se optimiza utilizando un tipo de
estructuras datos que son los arreglos, los arreglos
(específicamente un vector) son un tipo especial de objeto y
permiten almacenar un conjunto de elementos de un mismo
tipo, por ejemplo enteros, o String o char u objetos, pero no
mezclados.
El compilador de Java trata a los arreglos de la misma manera
que a una variable, es decir se declaran, se inicializan y
posteriormente se utilizan.
Nota: Si te interesa seguir el tema de programación Web
con Java, puedes revisar miCurso de Programación Java
Web, con JSP, Servlet y JPA donde aprenderás paso a paso
como desarrollar aplicaciones web con Java.
ARREGLOS UNIDIMENSIONALES (VECTORES, ARRAYS, ARREGLOS)
La sintaxis para declarar e inicializar un vector es la siguiente:
En donde:
1 miArreglo[1]=7;
1 package com.ecodeup.arreglos;
2
3 import java.util.Scanner;
4
5 public class TestArreglos {
6 public static void main(String[] args) {
7 Scanner entrada = new Scanner(System.in);
8 float promedio = 0;
9 float suma = 0;
10 int mayor = 0;
11 int menor = 0;
12
13 int[] miArreglo = new int[10];
14 for (int i = 0; i < 10; i++) {
15 System.out.print("Ingrese el número en la posición " + (i) + " :");
16 miArreglo[i] = entrada.nextInt();
17 }
18 // realizar la suma, promedio y el mayor
19 for (int i = 0; i < miArreglo.length; i++) {
20 suma += miArreglo[i];
21 if (mayor < miArreglo[i]) {
22 mayor = miArreglo[i];
23 }
24 System.out.println(String.format("Posición [%d] Elemento: %d", i,
25 miArreglo[i]));
26 }
27 menor = mayor;
28 // buscar el menor
29 for (int i = 0; i < miArreglo.length; i++) {
30 if (menor > miArreglo[i]) {
31 menor = miArreglo[i];
32 }
33 }
34 //promedio
35 promedio = suma / miArreglo.length;
36 System.out.println("***Salida***");
37 // contar las veces que se repite cada número
38 int cont;
39 for (int i = 0; i < miArreglo.length; i++) {
40 cont = 0;
41 for (int j = i; j < miArreglo.length; j++) {
42 if (miArreglo[i] == miArreglo[j]) {
43 cont++;
44 }
45 }
46 System.out.println(String.format("El número %d se repite %d veces",
47 miArreglo[i], cont));
48 }
49 System.out
50 .println(String
51 .format("La suma es %.2f, el promedio es %.2f, el mayor
52 es %d, el menor es %d",
53 suma, promedio, mayor, menor));
54 }
55
}
En donde:
1 int var=miMatriz[0][2];
1 package com.ecodeup.matrices;
2
3 import java.util.Scanner;
4
5 public class TestMatriz {
6
7 public static void main(String[] args) {
8 int matriz[][] = new int[3][3];
9
10 Scanner entrada = new Scanner(System.in);
11 float sumaFila = 0;
12 for (int i = 0; i < matriz.length; i++) {
13 for (int j = 0; j < matriz.length; j++) {
14 System.out.print("Ingrese el número en la fila " + (i)
15 + " columna " + j + " :");
16 matriz[i][j] = entrada.nextInt();
17 }
18 }
19 for (int i = 0; i < matriz.length; i++) {
20 sumaFila = 0;
21 for (int j = 0; j < matriz[i].length; j++) {
22 sumaFila += matriz[i][j];
23 System.out.print(String.format(" %d ", matriz[i][j]));
24 }
25 System.out.print(String.format(
26 " Suma fila: %f, promedio fila: %f ", sumaFila, sumaFila
27 / matriz.length));
28 System.out.println();
29 }
30 }
31 }