当前位置 博文首页 > weixin_45834750的博客:Java递归求阶乘,考虑程序的健壮性
import java.math.BigInteger;
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
Scanner sc =null;
while (true){
try {
System.out.println("请输入一个正整数:");
sc = new Scanner(System.in);
int n = sc.nextInt();
if(n<0){
System.out.print("您输入的数据不合法,");
}else{
BigInteger bigInteger = factorial(n);
System.out.println(n+"的阶乘值为:"+bigInteger);
break;
}
}catch (Exception e){
System.out.print("您输入的数据不合法,");
}
}
sc.close();
}
public static BigInteger factorial(int n){
if(n==0){
BigInteger bi = new BigInteger(String.valueOf(1));
return bi;
}else{
BigInteger b1 = new BigInteger(String.valueOf(n));
BigInteger b2 = new BigInteger(String.valueOf(factorial(n-1)));
return b1.multiply(b2);
}
}
}
cs