0% encontró este documento útil (0 votos)
25 vistas15 páginas

Arrays

Cargado por

Kike Zozo
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
25 vistas15 páginas

Arrays

Cargado por

Kike Zozo
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 15

Un array Java es una estructura de datos que nos permite almacenar una ristra de datos de

un mismo tipo. El tamaño de los arrays se declara en un primer momento y no puede cambiar
en tiempo de ejecución como puede producirse en otros lenguajes. La declaración de un
array en Java y su inicialización se realiza de la siguiente manera:

1)
public class array1 {

public static void main(String[] args) {


// TODO Auto-generated method stub

int [] matriz1 = {1,2,3,4,5,6};

int tamaño_matriz = matriz1.length;

for (int i=0;i<tamaño_matriz;i++) {

System.out.println("valor de la matriz " +i+ " = " + matriz1[i]);

}
}
}

1.1)
public class array1 {

public static void main(String[] args) {


// TODO Auto-generated method stub

int [] matriz1= {1,2,3,4,5,6};

for (int i=0;i<matriz1.length;i++) {

System.out.println("valor de la matriz " +i+ " = " + matriz1[i]);

}
}

2)

public class array2 {

public static void main(String[] args) {


// TODO Auto-generated method stub

int [] matriz1= new int [5];

matriz1[0]=1;
matriz1[1]=2;
matriz1[2]=3;
matriz1[3]=4;
matriz1[4]=5;

for (int i=0;i<matriz1.length;i++) {


System.out.println("valor de la matriz " +i+ " = " +
matriz1[i]);
}
}
}

3)

public class array3 {

public static void main(String[] args) {


// TODO Auto-generated method stub

int [] matriz1= new int [5];

for (int i=0;i<matriz1.length;i++) {


matriz1[i]=i;
}

for (int i=0;i<5;i++) {


System.out.println("valor de la matriz " +i+ " = " +
matriz1[i]);
}
}

4)

import java.util.Scanner;
public class array4 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner leer= new Scanner(System.in);

int [] matriz1= new int [5];


for (int i=0;i<5;i++) {
System.out.println("introduce el array numero " +i);
matriz1[i]=leer.nextInt();
}

for (int i=0;i<matriz1.length;i++) {


System.out.println("valor del array " +i+ " es igual a " +
matriz1[i]);
}
}

5)

public class array5 {

public static void main(String[] args) {


// TODO Auto-generated method stub

int [] matriz1= new int [5];


matriz1[0]=1;
matriz1[1]=2;
matriz1[2]=3;
matriz1[3]=4;
matriz1[4]=5;

for (int i:matriz1) {


System.out.println("valor de la matriz = "+ i);
}
}

INSTRUCCIÓN FOR EACH Y METODO RANDOM

for ( TipoARecorrer nombreVariableTemporal : nombreDeLaColecciónArray ) {


Instrucciones
}

Random rnd = new Random();


int month = rnd.next(1, 13); // creates a number between 1 and 12
int dice = rnd.next(1, 7); // creates a number between 1 and 6
int card = rnd.next(52); // creates a number between 0 and 51

6)
import java.util.Random;

public class array6 {

public static void main(String[] args) {


Random x = new Random();
int[] matriz_random = new int[5];

for (int i = 0; i < matriz_random.length; i++) {


matriz_random[i] = (int)x.nextInt(50);
}
for(int enteros:matriz_random) {
System.out.print(enteros + " ");
}
}
}

Ejercicios ARRAY 7

Leer 7 números por consola e imprimirlos.

import java.util.Scanner;

public class array7 {


public static void main(String[] args) {
int t[] = new int[7];
Scanner leer = new Scanner(System.in);
for (int i = 0; i < 7; i++) {
System.out.print("Introduzca un número: ");

t[i] = leer.nextInt();

}
System.out.println("Los números son:");
for (int i = 0; i < 7; i++) {
System.out.println(t[i]);
}

}
}

Leer 7 números por consola e imprimirlos en orden inverso.

import java.util.Scanner;

public class array8 {


public static void main(String[] args) {
int matriz[] = new int[7];
Scanner leer = new Scanner(System.in);
for (int i = 0; i < 7; i++) {
System.out.print("Introduzca un número: ");

matriz[i] = leer.nextInt();

}
System.out.println("Los números son:");
for (int i = 6; i >= 0; i--) {
System.out.println(matriz[i]);
}

}
}

EJERCICIO 3 ARRAYS

 CREAMOS UNA MATRIZ CON LOS NOMBRES DE UNOS CLIENTES


{"antonio", "pepe","jose", "miguel", "david"};
 CREAMOS OTRA MATRIZ DONDE VAMOS A GUARDAR 5 NUEVOS CLIENTES

EL PROGRAMA DEBE DE PEDIRNOS QUE INSERTEMOS LOS NUEVOS CLIENTS DE LA SIGUIENTE


MANERA:

Introduce el nombre de los 5 nuevos clientes


insterte el numero 1 MIGUEL
insterte el numero 2 PEDRITO
insterte el numero 3 ANTONIO
insterte el numero 4 ALVARO
insterte el numero 5 RAMON

LUEGO DEBE DE DARNOS UNA SERIE DE ALTERNATIVAS A ELEGIR:

¿que desea hacer?

1- IMPRIMIR TODOS LOS CLIENTES


2- IMPRIMIR UN SOLO CLIENTE (NOS PREGUNTARÁ CUAL DESPUES DE ELEGIR ESTA
OPCIÓN)
3- BUSCAR SI ALGUN CLIENTE YA EXISTIA
4- SALIR

Y POR SUPUESTO QUE EJECUTE CADA ALTERNATIVA LO QUE INDICA.

import java.util.Scanner;

public class array9 {


public static void main(String[] args) {
String matriz[] = new String[5];
String matrizbase[]= {"antonio", "pepe","jose", "miguel", "david"};
int selec;
Scanner leer = new Scanner(System.in);
System.out.println("Introduce el nombre de los 5 nuevos clientes");
for (int i = 1; i < 6; i++) {
System.out.print("insterte el numero " + i+ " ");
matriz[i-1] = leer.next();
}
System.out.println("¿que desea hacer?\n 1- IMPRIMIR TODOS LOS
CLIENTES\n 2- IMPRIMIR UN SOLO CLIENTE \n 3- BUSCAR SI ALGUN CLIENTE YA EXISTIA
\n 4- SALIR");
selec=leer.nextInt();

switch(selec){
case 1:
for (String toda:matriz) {
System.out.println(toda);
}
break;
case 2:
System.out.println("¿QUE NUMERO DE CLIENTE QUIERES
IMPRIMIR?");
int selec2;
selec2=leer.nextInt();
System.out.println(matriz[selec2-1]);
break;
case 3:
for(int j=0;j<matriz.length;j++) {
for(int k=0;k<matrizbase.length;k++) {
boolean sino =
matriz[j].equalsIgnoreCase(matrizbase[k]);
if (sino==true){
System.out.println("el cliente "+matriz[j]+ "
ya existe");
}

}
break;
case 4:break;
} leer.close();
}
}

EJERCICIO 4. CREARMOS UNA CLASE, ARRAY3. DENTRO DEFINIMOS UNA MATRIZ


UNIDIMENSIONAL CON LOS ELEMENTOS. {“antonio", "pepe","jose", "miguel", "david }

 NUESTRO PROGRAMA DEBE DE PREGUNTARNOS QUE USUARIOS QUEREMOS BUSCAR


 EL RESULTADO DEBE DE SER SI EXISTE O NO.
 SI EXISTE, IMPRIME EL USUARIO Y EL ÍNDICE DEL ELEMENTO DE LA MATRIZ

import java.util.Scanner;

public class array9 {


public static void main(String[] args) {
String matriz[] = new String[5];
String matrizbase[]= {"antonio", "pepe","jose", "miguel", "david"};
int selec;
Scanner leer = new Scanner(System.in);
System.out.println("Introduce el nombre de los 5 nuevos clientes");
for (int i = 1; i < 6; i++) {
System.out.print("insterte el numero " + i+ " ");
matriz[i-1] = leer.next();
}
System.out.println("¿que desea hacer?\n 1- IMPRIMIR TODOS LOS
CLIENTES\n 2- IMPRIMIR UN SOLO CLIENTE \n 3- BUSCAR SI ALGUN CLIENTE YA EXISTIA
\n 4- SALIR");
selec=leer.nextInt();

switch(selec){
case 1:
for (String toda:matriz) {
System.out.println(toda);
}
break;
case 2:
System.out.println("¿QUE NUMERO DE CLIENTE QUIERES
IMPRIMIR?");
int selec2;
selec2=leer.nextInt();
System.out.println(matriz[selec2-1]);
break;
case 3:
for(int j=0;j<matriz.length;j++) {
for(int k=0;k<matrizbase.length;k++) {
boolean sino =
matriz[j].equalsIgnoreCase(matrizbase[k]);
if (sino==true){
System.out.println("el cliente "+matriz[j]+ "
ya existe");
}

}
break;
case 4:break;
} leer.close();
}
}
Con este programa terminamos los ejercicios de estructuras y matrices. El fin
de este ejercicio es poner en práctica todo lo aprendido hasta ahora y
desarrollar la destreza de programador que llevamos dentro.
En Java hay clases con métodos para casi todo, pero a veces tenemos que
construir las nuestras propias para una tarea determinada. Por todo esto
vamos a hacer un mini-juego sobre la consola que nos suponga un desafío
con estas características.
Desarrollo:
En nuestro caso, vamos a hacer un hundir los barcos sencillo.
El programa será totalmente libre pero como mínimo deberá contener los puntos siguientes.

- Los barcos deben de guardarse dentro de alguna matriz.


- Los barcos solo ocuparán dos índices de la matriz, ya que es suficiente para jugar.
- Se crean dos barcos que ocuparan posiciones aleatorias en la matriz, además uno en
vertical y el otro en horizontal.
- Los dos barcos no pueden coincidir en ningún índice del tablero.
- El programa debe de seguir el formato que se ve a continuación.

Bienvenido al hundir los barcos por cortesía de los alumnos de DAM.

Instrucciones: Este es el tablero de juego, en él se crean 2 barcos en


posiciones aleatorias.

Uno se encuentra en posición vertical y otro en posición horizontal, el tamaño


de ambos es de 2 casillas

1 2 3 4
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
4 0 0 0 0

PULSA START PARA EMPEZAR EL JUEGO O EXIT PARA SALIR

1-START
2-SALIR
- Cuando seleccionemos START nos debe de pedir las coordenadas que pueden ser:
DE LA (1,1) A LA (4,4)
Véase el ejemplo.

lanza la bomba!, dame las coordenadas


primera!1
segunda!1

- En el caso que no acertemos nos debe de decir:

AGUA!!lanza la bomba!, dame las coordenadas


primera!

- En el caso de que acertemos nos debe de decir:

***************
* TOCADO!!! *
***************
lanza la bomba!, dame las coordenadas
primera!

- Cuando hemos tocado un barco, el siguiente punto sabemos que queda alrededor del
punto que hemos tocado. Una vez acertado el segundo punto nos debe aparecer:

***************
* TOCADO!!! *
***************
***************
* Y HUNDIDO! *
***************

lanza la bomba!, dame las coordenadas


primera!

- Si volvemos a lanzar una bomba en un punto ya impactado nos debe de decir que es agua.

- Cuando encontremos y hundamos los dos barcos nos dirá:

***************
* TOCADO!!! *
***************
***************
* Y HUNDIDO! *
***************

¡¡Enhorabuena, has hundido los barcos, tu ganas!!

Este era el tablero y ahí estaba los barcos hundidos.

1 2 3 4
1 x x 0 x
2 0 0 0 x
3 0 0 0 0
4 0 0 0 0

FIN DEL PROGRAMA

El juego es mejorable, todo lo que puedas aportar te puntuará positivamente.


Fecha de entrega, el 15 de Diciembre.
import java.util.Random;
import java.util.Scanner;

public class undirbarcos1 {

public static void main(String[] args) {// tenemos que meter los barcos
// TODO Auto-generated method stub
int clave;
int contador=0;
int posinibar1; //posicion inicial barco 1
int posinibar2; //posicion inicial barco 2
int [][] matriz = new int [4][4]; //matriz de barcos
char [][] matriz2=new char [4][4]; // matriz de representacion x para barco
Random aleatorio=new Random();
Scanner leer=new Scanner (System.in);
int suma=0,primera=0,segunda=0,suma2=0;

System.out.println("Bienvenido al hundir barcos por cortesía de los alumnos de


DAM.");
System.out.println("");
System.out.println("Instrucciones: Este es el tablero de juego, en el se crean 2
barcos en posiciones aleatorias.");
System.out.println("");
System.out.println("Uno se encuentra en posicion vertical y otro en posicion
horizontal, el tamaño de ambos es de 2 casillas");
System.out.println("");
System.out.println("\t 1 2 3 4 ");
System.out.println("\t1 0 0 0 0 ");
System.out.println("\t2 0 0 0 0 ");
System.out.println("\t3 0 0 0 0 ");
System.out.println("\t4 0 0 0 0 ");
System.out.println("");
System.out.println(" PULSA START PARA EMPEZAR EL JUEGO O EXIT PARA
SALIR");
System.out.println("");
System.out.println("\t\t\t1-START\n\t\t\t2-SALIR");clave=leer.nextInt();

for(int ñ=0;ñ<4;ñ++) {
for(int o=0;o<4;o++) {
matriz2[ñ][o]='0';
}
}

switch (clave) {

case 1:
do {

for(int ñ=0;ñ<4;ñ++) {
for(int o=0;o<4;o++) {
matriz[ñ][o]=0;
suma=0;
}
}
posinibar1=aleatorio.nextInt(4);
posinibar2=aleatorio.nextInt(4);

for(int i=0;i<2;i++) { //pone a 1 las posiciones


del barco horizontal
matriz[posinibar1][i]=1;

}
for(int j=0;j<2;j++) {
matriz[j][posinibar2]=2; //pone a 2 las posiciones del barco
vertical
}
for(int k=0;k<4;k++) {
for(int l=0;l<4;l++) {
suma=suma+matriz[k][l];
}
}
} while (suma!=6);

do {
System.out.println("lanza la bomba!, dame las coordenadas");
System.out.print("primera!");
primera=leer.nextInt();System.out.print("segunda!"); segunda=leer.nextInt();
if(matriz[primera-1][segunda-1]==1||matriz[primera-1][segunda-1]==2) {
System.out.println("");
System.out.println("\t***************");
System.out.println("\t* TOCADO!!! *");
System.out.println("\t***************");

matriz[primera-1][segunda-1]=3;
contador++;

if(contador==2||contador==4) {
System.out.println("\t***************");
System.out.println("\t* Y HUNDIDO! *");
System.out.println("\t***************");
System.out.println("");

}
else {System.out.print(" AGUA!!");}
suma2=suma2+matriz[primera-1][segunda-1];
}while(suma2!=12);

System.out.println("enhorabuena, has hundido los barcos, tu ganas");


for(int m=0;m<4;m++) {
for(int n=0;n<4;n++) {
if(matriz[m][n]==3) {
matriz[m][n]=1;
}
}
}

for(int m=0;m<4;m++) {
for(int n=0;n<4;n++) {
if(matriz[m][n]==1) {
matriz2[m][n]='x';
}
}
}
System.out.println("");
System.out.println("Este es el tablero con tus barcos hundidos");
System.out.println("");
System.out.println("\t 1 2 3 4 ");
System.out.println("\t1 "+matriz2[0][0]+" "+matriz2[0][1]+" "+matriz2[0][2]+"
"+matriz2[0][3]);
System.out.println("\t2 "+matriz2[1][0]+" "+matriz2[1][1]+" "+matriz2[1][2]+"
"+matriz2[1][3]);
System.out.println("\t3 "+matriz2[2][0]+" "+matriz2[2][1]+" "+matriz2[2][2]+"
"+matriz2[2][3]);
System.out.println("\t4 "+matriz2[3][0]+" "+matriz2[3][1]+" "+matriz2[3][2]+"
"+matriz2[3][3]);

break;
case 2:
break;
default:
System.out.println("error, no existe eleccion");

}
}
}
Xº) ejercicio propio, un ejercicio por alumno usando todas las estructuras
Xº) ejercicios, por alumno de la pagina 160, métodos String.

EJERCICIOS TEMA 8, METODOS CON ARRAYS

import java.util.Scanner;

import java.util.Arrays;

;public class array_metodos {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String [] array = {"a","b","c","d","e","f","g"};

//B buscar un elemento del array y devolver el indice en que se encuentra


System.out.println("¿que letra quieres buscar");
String search = sc.next();
int index_array = Arrays.binarySearch(array,search);
if (index_array==-8) {System.out.println("no existe");}
else {System.out.println(search +" se encuentra en el indice del array
"+index_array);
}
// ojo con no meter un elemento que ya exista

System.out.println("");

//Copia el array num hasta la quinta posicion(este ultimo no incluido), devuelve


un array
System.out.println("¿hasta que indice no inclusive quieres copiar");
int end_sub_array1 = sc.nextInt();
String sub_array1[]=Arrays.copyOf(array,end_sub_array1);
System.out.println("el resultado es");
for (String print_sub_array1: sub_array1) {
System.out.print(" "+print_sub_array1);
}

//copia desde una posicion inicial hasta una posicion final


System.out.println("\n");

//Copia el array num hasta la quinta posicion(este ultimo no incluido), devuelve


un array
System.out.println("¿desde donde hasta donde quieres copiar el array?");
System.out.println("introduce el primer indice inclusive");
int from_sub_array2= sc.nextInt();
System.out.println("introduce el segundo indice no inclusive");
int end_sub_array2 = sc.nextInt();
String sub_array2[]=Arrays.copyOfRange(array,
from_sub_array2,end_sub_array2);
System.out.println("el resultado es");
for (String print_sub_array2: sub_array2) {
System.out.print(" "+print_sub_array2);
}

System.out.println("\n");

// E COMPARAR DOS ARRAYS


System.out.println("¿son iguales los resultados de los arrays anteriores?");
boolean eq_arrays =Arrays.equals(sub_array1, sub_array2);
if (eq_arrays) {System.out.println("Sí, son iguales");
}
else {System.out.println("No son iguales");
}

System.out.println("");

// F INICIALIZACION MASIVA DE ELEMENTOS DE UN ARRAY


System.out.println("vamos a rellenar el array entero con un valor");
System.out.println("¿que valor será?");
String fill_string= sc.next();
System.out.println("el resultado es");
Arrays.fill(array, fill_string);
for (String print_fill_array: array) {
System.out.print(" "+ print_fill_array);
}

System.out.println("\n");

//C convertir un Array en un String para imprimirla


int [] array2= {25,56,88};
String new_Str_array2 = Arrays.toString(array2);
System.out.println("el array2 de enteros se ha convertido a Strings ");
System.out.println("la impresion queda " + new_Str_array2);

System.out.println("\n");

//D ordenar numeros del array


int [] array3= {4,2,1,3};
System.out.println("el array3 = "+ Arrays.toString(array3) +" ordenado queda:");
Arrays.sort(array3);
System.out.println(Arrays.toString(array3));
// String new_Str_array3 = AArrays.toString(array3)); lo mismo
// System.out.println(new_Str_array3); lo mismo

// G clonar un array
int[] array_clone = array3.clone();
System.out.println("el clone es " +Arrays.toString(array3));

}
}
Ejercicio 1 metodos arrays

Copia el ejercicio de la primitiva y modifícalo de la siguiente


manera.
1º El programa nos pide la combinación.
2º Genera los números aleatorios
3º Nos dice si tenemos premio
4º Nos devuelve tanto la combinación ganadora como la
combinación elegida por el usuario ordenadas de menor a mayor.

Ejercicio 2 juego de tabú

También podría gustarte