38 lines
1.1 KiB
Java
38 lines
1.1 KiB
Java
import java.util.*;
|
|
|
|
public class Metodos3 {
|
|
public static void main(String[] args) {
|
|
boolean detener = false;
|
|
int num = 0;
|
|
while(!detener){
|
|
System.out.println("Introduce un numero: ");
|
|
num = leerEntero();
|
|
if(num < 0) {
|
|
System.out.println("Tiene que ser un numero positivo");
|
|
} else detener = true;
|
|
}
|
|
System.out.printf("El factorial de %d es %.2f\n", num, factorial(num));
|
|
}
|
|
private static double factorial(int n) {
|
|
double result = 1.00;
|
|
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");
|
|
sc.next();
|
|
}
|
|
}
|
|
sc.close();
|
|
return n;
|
|
}
|
|
}
|