import java.math.BigInteger;
import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        String input = scanner.nextLine();

        try {
            BigInteger num = new BigInteger(input);
            BigInteger result = factorial(num);
            System.out.println(num + "! = " + result);
        } catch (NumberFormatException e) {
            try {
                int hexIndex = input.indexOf("x");
                if (hexIndex != -1) {
                    String hexStr = input.substring(hexIndex + 1);
                    BigInteger num = new BigInteger(hexStr, 16);
                    BigInteger result = factorial(num);
                    System.out.println(hexStr + "! = " + result);
                } else {
                    System.out.println("输入不是一个整数!");
                }
            } catch (NumberFormatException ex) {
                System.out.println("输入不是一个整数!");
            }
        }
    }

    public static BigInteger factorial(BigInteger n) {
        if (n.compareTo(BigInteger.ZERO) == 0 || n.compareTo(BigInteger.ONE) == 0) {
            return BigInteger.ONE;
        } else {
            return n.multiply(factorial(n.subtract(BigInteger.ONE)));
        }
    }
}
``
java设计一个求!的方法结果为一个长整数。编写一个程序从键盘输人一个数给整数飞赋值然后调用求!的方法求 人!在程序中规划处理如下异常情况:①输人的数不是一个整数而是实数则不计算;② 输人的数据是一个十六进制表示形式的串如oxla则取串的后级部分1a转化为十进制数再进行计算。

原文地址: https://www.cveoy.top/t/topic/caZl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录