Ejercicio Par o Impar
Soy nuevo en este lenguaje y he visto, explorando un poco en opciones, una linda forma de verificar si lo que el usuario quiere ingresar es válido o no, se encuentra en el segundo bloque de código.
Gracias por leer!
import java.util.Scanner;
public class ifElses {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Verificacion verificacion = new Verificacion();
System.out.println("Ingresa un número para verificar si es par o impar:");
String numeroParImpar = scanner.nextLine();
if ((Verificacion.esEntero(numeroParImpar))) {
int numero = Integer.parseInt(numeroParImpar);
if ((numero % 2) == 0) {
System.out.println("El número es par.");
} else if ((numero % 2) != 0) {
System.out.println("El número es impar.");
}
} else {
System.out.println("Entrada no válida.");
}
}
}
public class Verificacion {
public static boolean esEntero(String str) {
if (str == null || str.isEmpty()) {
return false;
}
//Intenta agarrar el String str y transformarlo en Entero
try {
Integer.parseInt(str);
return true;
}
// En caso no lograr poder transformarlo en Entero,
// significa que hubo algun error, símbolo, etc.
// Que te interpuso y no dejo hacerlo.
// Agarra ese valor y arroja false
catch (NumberFormatException e) {
return false;
}
}
}