import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n; while (true) { System.out.print("请输入一个正整数(输入0退出循环):"); try { n = sc.nextInt(); } catch (Exception e) { System.out.println("错误的类型!"); sc.nextLine(); continue; } if (n == 0) { break; } System.out.printf("%d! = %d ", n, fact(n)); } System.out.println("再见!"); } private static long fact(int n) { if (n < 0) { System.out.println("错误的数值范围!"); return -1; } else { return factorial(n); } } private static long factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(--n); } } }
Java递归实现阶乘