usar metodo leer entero

This commit is contained in:
PC de clase committed 2026-10-26 13:00:14 +01:00
1 parent 591c09e37a
commit be1108d422
2 files changed
+42 -2

No files matched your search

+18 -1
View File
@@ -7,7 +7,7 @@ public class Metodos3 {
int num = 0;
while(!detener){
System.out.println("Introduce un numero: ");
num = sc.nextInt();
num = leerEntero();
if(num < 0) {
System.out.println("Tiene que ser un numero positivo");
} else detener = true;
@@ -20,4 +20,21 @@ public class Metodos3 {
while(n > 0) result *= (double)n--;
return result;
}
public static int leerEntero() {
Scanner sc = new Scanner(System.in);
boolean parar = false;
int n = 0;
while(!parar) {
try {
n = sc.nextInt();
parar = true;
} catch(Exception e){
System.out.println("Número invalido, intentalo otra vez");
} finally {
sc.next();
}
}
sc.close();
return n;
}
}