# Java 程序：使用`For`和`While`循环查找阶乘

> 原文： [https://beginnersbook.com/2017/09/java-program-to-find-factorial-using-for-and-while-loop/](https://beginnersbook.com/2017/09/java-program-to-find-factorial-using-for-and-while-loop/)

我们将编写三个 java 程序来查找数字的阶乘。 1）使用`for`循环 2）使用`while`循环 3）找到用户输入的数字的阶乘。在完成程序之前，让我们理解什么是阶乘：数字`n`的因子表示为`n!`，`n!`的值表示为：`1 * 2 * 3 * ... * (n-1) * n`

我们在程序中使用循环实现了相同的逻辑。要了解这些程序，您应该具备以下 [java 教程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)主题的基本知识：

*   [Java `For`循环](https://beginnersbook.com/2015/03/for-loop-in-java-with-example/)
*   [Java `while`循环](https://beginnersbook.com/2015/03/while-loop-in-java-with-examples/)

## 示例：使用`for`循环查找阶乘

```java
public class JavaExample {

    public static void main(String[] args) {

    	//We will find the factorial of this number
        int number = 5;
        long fact = 1;
        for(int i = 1; i <= number; i++)
        {
            fact = fact * i;
        }
        System.out.println("Factorial of "+number+" is: "+fact);
    }
}
```

**输出：**

```java
Factorial of 5 is: 120
```

## 示例 2：使用`while`循环查找阶乘

```java
public class JavaExample {

    public static void main(String[] args) {

    	//We will find the factorial of this number
        int number = 5;
        long fact = 1;
        int i = 1;
        while(i<=number)
        {
            fact = fact * i;
            i++;
        }
        System.out.println("Factorial of "+number+" is: "+fact);
    }
}
```

**输出：**

```java
Factorial of 5 is: 120
```

## 示例 3：查找用户输入的数字的阶乘

程序使用`while`循环查找输入数的阶乘。

```java
import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {

    	//We will find the factorial of this number
        int number;
        System.out.println("Enter the number: ");
        Scanner scanner = new Scanner(System.in);
        number = scanner.nextInt();
        scanner.close();
        long fact = 1;
        int i = 1;
        while(i<=number)
        {
            fact = fact * i;
            i++;
        }
        System.out.println("Factorial of "+number+" is: "+fact);
    }
}
```

输出：

```java
Enter the number: 
6
Factorial of 6 is: 720
```