如何在此代码中显示负数阶乘

how to show the negative number factorial in this code

我正在尝试制作一个计算器,但由于我的代码有些混乱,我无法继续。我试图计算一个数字的阶乘,如果它是正数则没有错误,但每次我输入一个负数时结果为 1,这是我的代码。

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

public class Factorial2 {

   public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
       System.out.print("Enter a number: ");
       int n = s.nextInt();
       String fact = factorial(n);
       System.out.println("Factorial is " + fact);
   }

   public static String factorial(int n) {
       BigInteger fact = new BigInteger("1");
       for (int i = 1; i <= n; i++) {
           fact = fact.multiply(new BigInteger(i + ""));
       }
       return fact.toString();
   }
}

我已经尝试制作 if 语句,但仍然会导致 1.i 还想将负阶乘变成显示文本而不是负阶乘的值

您需要在计算前验证输入,例如:

public static String factorial(int n) {
    if(n < 1) return "0";
    BigInteger fact = new BigInteger("1");
    for (int i = 1; i <= n; i++) {
        fact = fact.multiply(new BigInteger(i + ""));
    }
    return fact.toString();
}

当然您可以定义任何默认值 return 或抛出错误:

if(n < 1) throw new RuntimeException("Input must be > 0");