Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.
Archivo del blog
miércoles, 14 de septiembre de 2022
Mastermind 2. Uso de expresión regular para validar entrada de datos.
Código (Mastermind.java):
package mastermind;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Mastermind {
public static void main(String[] args) {
//presentación e instrucciones juego
System.out.println(""
+ "-------------\n"
+ " MASTER-MIND\n"
+ "-------------\n\n"
+ "Se trata de adivinar un número, si adivinas el número y el lugar correcto es un muerto, si aciertas el número pero no el lugar es un herido.\n"
+ "EJEMPLO: El número a decifrar es el <1234>\n"
+ "Si introduces el <2136>. Esto te dará:\n"
+ "1 muerto(el 3) y 2 heridos(1 y 2). El 6 al no estar no cuenta.\n\n"
);
//inicializar variables
List<String> valores = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
int i_hallar[] = new int[4];
int i_buscar[] = new int[4];
int muerto, herido, cont = 1;
String hallar = "", buscar;
Scanner input;
//generar código aleatorio
Collections.shuffle(valores); //mezclar valores
for (int i = 0; i < 4; i++) {
hallar += valores.get(i);
i_hallar[i] = Integer.parseInt("" + hallar.charAt(i));
}
//iniciar partida
System.out.println("Escriba número de 4 cifras (ej: 1234):\n");
do {
muerto = 0;
herido = 0;
//introducir y validar
do {
System.out.println(cont + "º intento:");
input = new Scanner(System.in);
buscar = input.nextLine();
} while (!ValidarNum(buscar));
for (int i = 0; i < 4; i++) {
i_buscar[i] = Integer.parseInt("" + buscar.charAt(i));
}
//búsqueda muertos y heridos
for (int i = 0; i < i_hallar.length; i++) {
for (int j = 0; j < i_buscar.length; j++) {
if (i_buscar[j] == i_hallar[i]) {
herido++;
if (j == i) {
herido--;
muerto++;
}
}
}
}
System.out.println(muerto + " muerto/s y " + herido + " herido/s\n");
} while (cont++ < 10 && muerto != 4);
//resultado final
if (muerto > 3) {
System.out.println("\nCódigo descifrado! " + Arrays.toString(i_hallar));
System.out.println("Has ganado!\n");
} else {
System.out.println("\nHas perdido!");
System.out.println("Código era " + Arrays.toString(i_hallar) + "\n");
}
}
private static boolean ValidarNum(String buscar) {
Boolean valido;
Pattern pat = Pattern.compile("^\\d{4}$");
Matcher mat = pat.matcher(buscar);
valido = mat.find();
if (!valido) {
System.out.println("\nCódigo <" + buscar + "> no válido, intente de nuevo.\n");
}
return valido;
}
}
Resultado:
run:
-------------
MASTER-MIND
-------------
Se trata de adivinar un número, si adivinas el número y el lugar correcto es un muerto, si aciertas el número pero no el lugar es un herido.
EJEMPLO: El número a decifrar es el <1234>
Si introduces el <2136>. Esto te dará:
1 muerto(el 3) y 2 heridos(1 y 2). El 6 al no estar no cuenta.
Escriba número de 4 cifras (ej: 1234):
1º intento:
d34456
Código <d34456> no válido, intente de nuevo.
1º intento:
3458
1 muerto/s y 1 herido/s
2º intento:
domingo, 11 de septiembre de 2022
Mastermind. Crear un juego sencillo.
Código (Mastermid.java):
package mastermind;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Mastermind {
public static void main(String[] args) {
//presentación e instrucciones juego
System.out.println("\n"
+ "-------------\n"
+ " MASTER-MIND\n"
+ "-------------\n\n"
+ "Se trata de adivinar un número, si adivinas el número y el lugar correcto es un muerto, si aciertas el número pero no el lugar es un herido.\n"
+ "EJEMPLO: El número a decifrar es el <1234>\n"
+ "Si tu introduces el <2136>. Esto te dará:\n"
+ "1 muerto(el 3) y 2 heridos(1 y 2). El 6 al no estar no cuenta.\n\n"
);
//inicializar variables
List<String> valores = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
int i_hallar[] = new int[4];
int i_buscar[] = new int[4];
int muerto, herido, cont = 1;
String hallar = "", buscar;
Scanner input;
//generar código aleatorio
Collections.shuffle(valores); //mezclar valores
for (int i = 0; i < 4; i++) {
hallar += valores.get(i);
i_hallar[i] = Integer.parseInt("" + hallar.charAt(i));
}
//System.out.println("Código decifrado: " + hallar);
//iniciar partida
System.out.println("Escriba número de 4 cifras (ej: 1234):\n");
do {
muerto = 0;
herido = 0;
do {
System.out.println(cont + "º intento:");
input = new Scanner(System.in);
buscar = input.nextLine();
if (buscar.length() != 4) {
System.out.println("Código no válido!\n");
}
} while (buscar.length() != 4);
for (int i = 0; i < 4; i++) {
i_buscar[i] = Integer.parseInt("" + buscar.charAt(i));
}
//búsqueda muertos y heridos
for (int i = 0; i < i_hallar.length; i++) {
for (int j = 0; j < i_buscar.length; j++) {
if (i_buscar[j] == i_hallar[i]) {
herido++;
if (j == i) {
herido--;
muerto++;
}
}
}
}
System.out.println(muerto + " muerto/s y " + herido + " herido/s\n");
} while (cont++ < 10 && muerto != 4);
//resultado final
if (muerto > 3) {
System.out.println("\nCódigo descifrado! " + Arrays.toString(i_hallar));
System.out.println("Has ganado!\n");
} else {
System.out.println("\nHas perdido!");
System.out.println("Código era " + Arrays.toString(i_hallar) + "\n");
}
}
}
Resultado:
run:
-------------
MASTER-MIND
-------------
Se trata de adivinar un número, si adivinas el número y el lugar correcto es un muerto, si aciertas el número pero no el lugar es un herido.
EJEMPLO: El número a decifrar es el <1234>
Si tu introduces el <2136>. Esto te dará:
1 muerto(el 3) y 2 heridos(1 y 2). El 6 al no estar no cuenta.
Escriba número de 4 cifras (ej: 1234):
1º intento:
4237
1 muerto/s y 1 herido/s
2º intento:
324
Código no válido!
2º intento:
6453
0 muerto/s y 1 herido/s
3º intento:
4712
2 muerto/s y 1 herido/s
4º intento:
4710
2 muerto/s y 2 herido/s
5º intento:
4701
4 muerto/s y 0 herido/s
Código descifrado! [4, 7, 0, 1]
Has ganado!
BUILD SUCCESSFUL (total time: 1 minute 12 seconds)
domingo, 28 de agosto de 2022
Generación de números primos.
Código (Limit.java):
package limit;
public class Limit {
public static void main(String[] args) {
boolean p;
int limit = 100;
String aux = "";
for (int n = 3; n < limit; n++) {
p = esPrimo(n);
aux += p ? n : "·";
}
System.out.println(aux);
}
private static boolean esPrimo(int n) {
//es numero par?
if (n % 2 == 0) {
return false;
}
//es numero multiplo del resto de numeros impares?
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Resultado:
run:
3·5·7···11·13···17·19···23·····29·31·····37···41·43···47·····53·····59·61·····67···71·73·····79···83·····89·······97··
BUILD SUCCESSFUL (total time: 0 seconds)