这是我的代码:
import java.util.*;
public class factorialdisplay {
// Main Method. Prints out results of methods below.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
// Asks user for input
System.out.println("Please enter a number: ");
int n = console.nextInt();
for (int i = 0; i <= n; ++i) {
System.out.println(i + "! = " + factorial(n));
}
}
public static int factorial (int n) {
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
return f;
}
return f;
}
}
我正在尝试获取输出:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
但是当我运行代码时,我得到了这个:
0! = 1
1! = 1
2! = 1
3! = 1
4! = 1
5! = 1
我的问题是,如何for
通过factorial
静态方法将循环的每次迭代的结果返回给该main
方法?